'iterator to a vector of vector of int
I have an error in the following code where I want to print the first element in each sub-vector:
vector<vector<int>> logs{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}};
for (auto beg = logs.begin(); beg != logs.end(); beg++) {
cout << *beg[0] << endl;
}
the error is from cout << *beg[0]...:
Indirection requires pointer operand ('std::vector<int, std::allocator<int>>' invalid)
So my question is: the dreference of the iterator should a sub-vector in the vector "logs", so I use subscript to access the first element of it. Why there's a std::vector<int, std::allocator<int>> object? Where does the std::allocator<int> come from? How can I access the elements in the sub-vectors?
Solution 1:[1]
The problem(cause of the mentioned error) is that due to operator precedence, the expression *beg[0] is grouped as(or equivalent to):
*(beg[0])
which can't work because beg is an iterator and has no [] operator. This is because the operator [] has higher precedence than operator *.
To solve this replace cout << *beg[0] << endl; with:
cout << (*beg)[0] << endl; //or use beg->at(0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anoop Rana |
