Reputation: 347
I couldn't find any solution for my problem. Let's assume that we've got n elements of such map:
std::map<string, string> tmpMap;
We've also got iterator to this map:
std::map<string, string>::iterator itTmpMap = tmpMap.begin();
How can I now change iterator to for example fourth pair? Compilator doesn't let me just add an integer to iterator.
Compilator error:
int a = 4;
itTmpMap = itTmpMap + a;
Upvotes: 0
Views: 170
Reputation: 311126
std::map
has a bidirectional iterator. Operation iterator + integral type is not defined for bidirectional iterators. So to get the equivalemt iterator of itTmpMap + 4 you have 4 times to increase it.
The C++ Standard defines special functions for such an operation. You can use either std::advance
that has return type void. For example
std::advance( itTmpMap, 4 );
Or you can use std::next
that return reference to the source incremented iterator. For example
std::next( itTmpMap, 4 );
For example to traverse the map starting with the fourth iterator you could write
std::for_each( std::next( tmpMap.begin(), 4 ), tmpMap.end(), SomeFunction );
Upvotes: 1
Reputation: 15870
The iterators for std::map
are bidirectional. There are several operations that are valid for such iterators, but adding an integer to move it is not one of them. There are a couple ways you can do this:
// this will advance the iterator 4 times
for (unsigned int i = 0; i < 4; ++i)
itTmpMap++;
Or, the preferred method
std::advance(itTmpMap, 4);
Upvotes: 0
Reputation: 1215
Use std::advance(itTmpMap, 4);
The map iterator is a bidirectional iterator, not a random-access iterator.
Upvotes: 2
Reputation: 942
You need to increment the iterator 4 times:
++itTmpMap;
++itTmpMap;
++itTmpMap;
++itTmpMap;
Upvotes: 0
Reputation: 33655
Use the function std::advance()
. It takes a reference, rather than returning a new iterator, an oddity which I've never understood...
Upvotes: 5