Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I go decrement the iterator of a std::map by a certain number?

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.

like image 367
Zebrafish Avatar asked Oct 23 '25 17:10

Zebrafish


2 Answers

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.

like image 170
Holt Avatar answered Oct 26 '25 05:10

Holt


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

like image 32
Arnav Borborah Avatar answered Oct 26 '25 05:10

Arnav Borborah