我有一个 vector 数组,但由于某些原因我无法遍历 vector 数组。它反而给了我这么长的错误信息。
int num = 6;
vector<string> vArray[num];
for (int i = 0; i < 50; i++)
{
vArray[i % num].insert(vArray[i].begin(), data);
} //runs fine
for (int i = 0; i < num; i++)
{
for(std::vector<int>::iterator it = vArray[i].begin(); it != vArray[i].end(); it++)
{
cout << *it << endl;
}
}//problem..
它只是给我这个超长的错误信息
p2.cpp:94: 错误:从'__gnu_cxx::__normal_iterator, std::allocator >*, std::vector, std::allocator >, std::allocator, std::allocator >> >> ' 请求非标量类型 '__gnu_cxx::__normal_iterator >>'
p2.cpp:94: 错误:'it != vArray[i].std::vector<_Tp, _Alloc>::end with _Tp = std::basic_string, std 中的'operator!=' 不匹配::allocator >, _Alloc = std::allocator, std::allocator >>'
最佳答案
看行:
vArray[i % num].insert(vArray[i].begin(), data);
现在当 i=6 时,它说:
vArray[0].insert(vArray[6].begin(), data);
并且 vArray[6] 未定义
第二个问题是您使用了 std::vector<int>::iterator
对于 std::vector<string>
你真的可以使用关键字 auto 来避免这些错误
尝试以下操作:
for(auto it = vArray[i].begin(); it != vArray[i].end(); it++)
这意味着即使您更改 vArray 中的类型,for 循环也将在假设 c++11 的情况下工作
关于c++ - 基本迭代器 C++ 如何迭代 vector 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21568882/