Nivetha
Nivetha

Reputation: 708

How to iterate over a specific set of keys in c++ maps?

I am iterating over a C++ map. Say I want to obtain the keys present in the map except the first 2. The keys are sorted in map. Hence I thought of using something like this:

map<int, int> table;
for( auto i = table.begin()+2; i != table.end(); i++ )
  cout<<i->first<<"\t"<<i->second<<endl;

Though this works with vectors, it throws an error with maps due to the '+' operator not being implemented for maps. One way the result can be achieved is :

auto i = table.begin();
int count = 0;
while( count < 2 && i != table.end() ){
  count++;
  i++;
}
for( ; i!=table.end(); i++ )
  cout<<i->first<<"\t"<<i->second<<endl;

Is there any other efficient way to implement this?

Upvotes: 6

Views: 562

Answers (1)

user657267
user657267

Reputation: 21040

It's no more efficient but perhaps a little easier to read

for (auto i = std::next(table.begin(), 2); i != table.end(); i++)

Upvotes: 8

Related Questions