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?
It's no more efficient but perhaps a little easier to read
for (auto i = std::next(table.begin(), 2); i != table.end(); i++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With