Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 256
Nivetha Avatar asked Sep 03 '15 00:09

Nivetha


1 Answers

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

for (auto i = std::next(table.begin(), 2); i != table.end(); i++)
like image 76
user657267 Avatar answered Oct 22 '22 18:10

user657267