所以我正在练习STL字符串类,但是我无法弄清楚为什么string-> length函数不会给出5的正确答案,而只有2(无论实际长度)。这是我要运行的程序,但它认为-> begin和-> end之间只有2个项目:

void testFunc(string _string[])
{
      int _offset = 0;
      string::const_iterator i;
      for (i = _string->begin(); i != _string->end(); i++)
      {
           cout << _offset << "\t";
           cout << _string[_offset] << endl;
           _offset ++;
      }
};

int main()
{
     string Hello[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};

     testFunc(Hello);

     char response;
     cin >> response;
     return 0;
}

输出为:
0     Hi
1     Holla

谢谢! =)

最佳答案

您正在遍历第一个字符串“Hi”-它有两个字符,因此您看到两个条目。

如果要使用所有STL,则需要一个 vector 而不是C样式的数组(即vector<string>),并在其上使用迭代器。

如果您不想要STL:

    void testFunc(string *strings, int stringCount)
    {
        int _offset = 0;

        while (stringCount--)
        {
            cout << _offset << "\t";
            cout << _strings[_offset] << endl;
            _offset ++;
        }
    };

int main()
{
    string Hello[] = {"Hi", "Holla", "Eyo", "Whatsup", "Hello"};

    testFunc(Hello, sizeof(Hello) / sizeof(Hello[0]));

    char response;
    cin >> response;
    return 0;
}

10-08 09:28
查看更多