ACC
ACC

Reputation: 2560

C++ Iterate from the second element of a map

I have a std::multimap on which I am iterating using a forward iterator.

std::multimap<int,char>::iterator it;
for(it=map.begin();it!=map.end();++it) {
    // do something
}

Now I need to treat the first element differently and start iterating from the second element of the map. How do I do that?

Upvotes: 5

Views: 16964

Answers (6)

Shubham Kumar Gupta
Shubham Kumar Gupta

Reputation: 1147

you can directly use this

unordered_map<int,int> map;

n = 1
auto it = std::next(map.begin(), n);

int key = it->first

Upvotes: 0

Vin&#237;cius
Vin&#237;cius

Reputation: 15718

std::multimap<int,char>::iterator it = map.begin();
//treat it here
++it
for(;it!=map.end();++it) {

}

Upvotes: 2

Tomas
Tomas

Reputation: 176

Seems it looks shorter

it = ++map.begin(); 

Upvotes: 6

Pete Becker
Pete Becker

Reputation: 76245

Change it = map.begin() in the for-initializer to it = map.begin(), ++it.

Upvotes: 1

Christian Stieber
Christian Stieber

Reputation: 12496

for(bool First=true, it=map.begin();it!=map.end();++it) {
    if (First) { do something; First=false; }
    else { do something else; }
}

or, if you prefer:

iterator it=map.begin();
if (it!=map.end()) { do something; ++it; }
for (; it!=map.end(); ++it) { do something }

Upvotes: 1

jrok
jrok

Reputation: 55395

std::multimap<int,char>::iterator it;

for(it = std::next(map.begin()); it != map.end(); ++it) {
    // do something
}

This is C++11 only. You'll need to include <iterator>.

The other option is obvious, but less pretty:

it = map.begin();
++it;
for(; it != map.end(); ++it) {
    // do something
}

Take a look at std::advance, too.

Upvotes: 12

Related Questions