Is there a reason that the STL does not provide functions to return an iterator into a container via an index?
For example, let’s say I wanted to insert an element into a std::list but at the nth position. It appears that I have to retrieve an iterator via something like begin() and add n to that iterator. I’m thinking it would be easier if I could just get an iterator at the nth position with something like, std::list::get_nth_iterator(n).
I suspect I have misunderstood the principles of the STL. Can anyone help explain?
Thanks
BeeBand
You can use
advance()from the<iterator>header:list<foo>::iterator iter = advance(someFooList.begin(), n);If the iterator supports random access (like
vector) it’ll work quite efficiently, if it only supports increasing (or decreasing) the iterator, likelist, it’ll work but only as well as can be.