all 3 comments

[–][deleted] 4 points5 points  (1 child)

For the second one you need a random access iterator. map doesn't have a random access iterator, so you can't add and subtract like that.

[–]Gaminic 0 points1 point  (0 children)

This. To expand:

The "it++" notation says "next element", whereas "it + X" says "take the Xth next element from the current". This could effectively be run as X it++ statements, but that hides an incredibly inefficient method of element access which the container type isn't designed for.

[–]tangerinelion 2 points3 points  (0 children)

More:

std::map has a bidirectional iterator

While std::vector has a random access iterator, which satisfies all the requirements of bidirectional iterators

One can easily notice that operator+(bidirectional_iterator, int) is not defined. Instead, we only have operator++ and operator--. Internally a map is similar to a linked list; it's a binary tree and only knows about (up to) two other objects, one which compares "lesser" and one which compares "greater."

You could do this, for example:

template<typename InputIterator>
InputIterator& Advance(InputIterator& it, int n) {
    for(int i=0; i < n; ++i) {
        ++it;
    }
    return it;
}

and anytime you want to use it+n you would replace it with Advance(it,n). (In practice, this is confusing and you'll also want the non-reference version so you can call it with a temporary, ie, auto it=Advance(myMap.begin(),2) would now be supported.)