Nowax
Nowax

Reputation: 347

C++: Iteration of the map

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

Answers (5)

Vlad from Moscow
Vlad from Moscow

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::nextthat 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

Zac Howland
Zac Howland

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

Dmitry Markin
Dmitry Markin

Reputation: 1215

Use std::advance(itTmpMap, 4); The map iterator is a bidirectional iterator, not a random-access iterator.

Upvotes: 2

Alex
Alex

Reputation: 942

You need to increment the iterator 4 times:

++itTmpMap;
++itTmpMap;
++itTmpMap;
++itTmpMap;

Upvotes: 0

Nim
Nim

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

Related Questions