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) << " ";
}
I'm getting this error:
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>>>>>
How should I solve this??
CodePudding user response:
The problem is that it
is an iterator to 1D vector<int>
while b8.begin()
gives us an iterator to a 2D vector<vector<int>>
. So these iterators are not compatible with each other. That is, you cannot use the iterator it
to traverse a 2D vector.
You can solve this by changing vector <int> ::iterator it;
as shown below:
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
}
}
Another option would be to use auto
with range-based for
loop as shown below:
for (auto &row: v8)
{
for(auto &col: row)
{
cout << col << " ";
}
}
CodePudding user response:
To iterate through vectors in v8
, enumerating their elements, use range-based for
loops.
for (auto& v: v8) {
for (auto& it: v) {
std::cout << it << ' ';
}
}