向量和字符串C++

Vectors and Strings C++

本文关键字:C++ 字符串 向量      更新时间:2023-10-16
#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
int main()
{
    vector<string> test;
    test.push_back("yasir");
    test.push_back("javed"); 
    for(int i=0; i!=test.end();i++)
    {
        cout << test[i];
    }
}

为什么这段代码会放弃错误?我无法确定错误的原因。错误:运算符不匹配!=....

首先,您尝试将int与向量的迭代器进行比较。

for(int i=0; i!=test.end();i++)
{
    cout << test[i];
}

在这里,test.end()返回迭代器。没有重载operator!=可以将整数(int i = 0(与该迭代器(test.end()(进行比较。

所以你的循环应该看起来更像:

for (std::vector<string>::iterator i = test.begin(); i != test.end(); i++)
{
    cout << *i;
}

如果使用 C++11 或更高版本,则可以将std::vector<string>::iterator替换为 auto

接下来,您包含了包含旧函数<string.h>,例如:strlenstrcpy 。同样,<cstring>包含 C 样式字符串。

如果你想使用operator<<,所以如果你想写:cout <<那么你必须做:#include <string>

如前所述,问题是,您尝试将整数与 for 语句"中间"的迭代器进行比较。试试这个,从我的角度来看更直观

#include <vector>
#include <iostream>
#include <cstring>
#include <string.h>
using namespace std;
    int main()
    {
        vector<string> test;
        test.push_back("yasir");
        test.push_back("javed"); 
        for(int i=0; i<test.size();++i)
        {
            cout << test[i];
        }
    }