With an std::vector I can do:
std::vector<int> h;
auto it = h.end() - 2;
But with the std::map I can't do:
std::map<int, int> h;
auto it = h.end() - 2;
I can only do:
auto it = --h.end();
This is for example if I want the member two from the end, or three from the end, or whatever.
You can use std::advance:
auto it = h.end();
std::advance(it, -4);
Note that the complexity is linear in n (the second parameter) for std::map iterators (which are not random access iterators), meaning that there is no "magic" and a call to std::advance is equivalent to applying n times the increment/decrement operator on the iterator.
On the other hand, you can also use std::prev, as follows:
auto it = std::prev(iter, 2);
Internally, this does the same thing as std::advance (using it, in fact), except it could be said that this is somewhat clearer.
If you were wondering why you couldn't subtract a map iterator unlike a vector iterator, the reason for this is because std::vector<T>::iterator is a RandomAccessIterator, meaning it "can be moved to point to any element in constant time"1 through addition/subtraction. On the other hand, std::map<T,U>::iterator is a BidirectionalIterator, which can go in either direction, but only in increments of one.
1 http://en.cppreference.com/w/cpp/concept/RandomAccessIterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With