Wei Zhang
Wei Zhang

Reputation: 325

Why I can't use `+1` in the iterator of `map` in c++?

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

Answers (2)

R Sahu
R Sahu

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. add N*sizeof(T) to a T*), whereas doing the same thing for a bidirectional iterator would require applying ++ N times.

Upvotes: 7

songyuanyao
songyuanyao

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

Related Questions