Reputation: 325
I have a problem about the iterator using in map
. I have a map with type of map<int, vector<int> > vpmap;
I want to loop through the whole map. Then I use
for (size_t i = 0; i < vpmap.size(); i++) {
{
auto it = vpmap.begin();
it++;
/*code*/
}
This is well. But when I replace the it++
to it=it+1
. The complier gives an error. I haven't get this error before when using vector
. I would like to know the reason of it.
Upvotes: 3
Views: 959
Reputation: 206557
std::vector::iterator
is a LegacyRandomAccessIterator. It is required to support the operation it + 1
.
On the other hand, std::map::iterator
is a LegacyBidirectionalIterator. It is not required to support it + 1
but it is required to support it++
as well as it--
.
Relevant detail from an answer to a different post:
The reason behind this is that adding
N
to a random access iterator is constant time (e.g. addN*sizeof(T)
to aT*
), whereas doing the same thing for a bidirectional iterator would require applying++
N
times.
Upvotes: 7
Reputation: 172864
it
is the iterator of std::map
, it's an Bidirectional Iterator and doesn't support operator+
.
RandomAccess Iterator supports operator+
, e.g. the iterator of std::vector
, that's why you did not get this error with std::vector
.
Upvotes: 5