使用开始和结束迭代器时出错
Getting an error while using begin and end iterators
vector <vector<int> > v8;
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
int n;
cin >> n;
vector <int> temp;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
temp.push_back(x);
}
v8.push_back(temp);
}
vector <int> ::iterator it;
for (it = v8.begin(); it < v8.end(); it++)
{
cout << (*it) << " ";
}
我收到这个错误:
no operator "=" matches these operandsC/C++(349)
intro.cpp(161, 13): operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>> = __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int>> *, std::vector<std::vector<int, std::allocator<int>>, std::allocator<std::vector<int, std::allocator<int>>>>>
我该如何解决??
问题是it
是一个迭代器到一维vector<int>
而b8.begin()
给我们一个 2D vector<vector<int>>
的迭代器。所以这些迭代器彼此不兼容。也就是说,你不能使用迭代器it
来遍历一个二维向量。
您可以通过更改 vector <int> ::iterator it;
来解决此问题,如下所示:
vector <vector<int>> ::iterator it; //change made here. Now it is an iterator to a 2D vector
for (it = v8.begin(); it != v8.end(); it++)
{
for(auto i = (*it).begin(); i != (*it).end();++i) // i is an iterator to a 1D vector
{
cout << (*i) << " ";//it changed to i
}
}
另一种选择是使用 auto
和 range-based for
循环,如下所示:
for (auto &row: v8)
{
for(auto &col: row)
{
cout << col << " ";
}
}
要遍历 v8
中的向量,枚举它们的元素,请使用 range-based for
循环。
for (auto& v: v8) {
for (auto& it: v) {
std::cout << it << ' ';
}
}
vector <vector<int> > v8;
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
int n;
cin >> n;
vector <int> temp;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
temp.push_back(x);
}
v8.push_back(temp);
}
vector <int> ::iterator it;
for (it = v8.begin(); it < v8.end(); it++)
{
cout << (*it) << " ";
}
我收到这个错误:
no operator "=" matches these operandsC/C++(349)
intro.cpp(161, 13): operand types are: __gnu_cxx::__normal_iterator<int *, std::vector<int, std::allocator<int>>> = __gnu_cxx::__normal_iterator<std::vector<int, std::allocator<int>> *, std::vector<std::vector<int, std::allocator<int>>, std::allocator<std::vector<int, std::allocator<int>>>>>
我该如何解决??
问题是it
是一个迭代器到一维vector<int>
而b8.begin()
给我们一个 2D vector<vector<int>>
的迭代器。所以这些迭代器彼此不兼容。也就是说,你不能使用迭代器it
来遍历一个二维向量。
您可以通过更改 vector <int> ::iterator it;
来解决此问题,如下所示:
vector <vector<int>> ::iterator it; //change made here. Now it is an iterator to a 2D vector
for (it = v8.begin(); it != v8.end(); it++)
{
for(auto i = (*it).begin(); i != (*it).end();++i) // i is an iterator to a 1D vector
{
cout << (*i) << " ";//it changed to i
}
}
另一种选择是使用 auto
和 range-based for
循环,如下所示:
for (auto &row: v8)
{
for(auto &col: row)
{
cout << col << " ";
}
}
要遍历 v8
中的向量,枚举它们的元素,请使用 range-based for
循环。
for (auto& v: v8) {
for (auto& it: v) {
std::cout << it << ' ';
}
}