map iterator doesn't have (+ n) iterator - any work around this?

Is there any particular reason why you can't assign a specific position to the iterator of a map?

e.g
1
2
3

map <string,bool>iterator it = myMap.end() - 1;// not allowed


And is also a way around this?

Thanks!
Is there any particular reason why you can't assign a specific position to the iterator of a map?


maps are not built for random access, so in order to advance X spaces, it has to follow a trail of linked pointers. This means it takes O(n) time and not O(1) time like you'd except a + or - operation to take.

And is also a way around this?


You can use std::advance:

1
2
std::advance( it, X );   // it += X
std::advance( it, -X );  // it -= X 


But again note that this will have O(n) time with a map.



EDIT: fixed advance example
Last edited on
@Disch

Super helpful, thanks so much!
Topic archived. No new replies allowed.