我在迭代C地图.假设我想获取除第一个之外的地图中存在的键.键在地图中排序.因此我想到使用这样的东西:
- map<int,int> table;
- for( auto i = table.begin()+2; i != table.end(); i++ )
- cout<<i->first<<"\t"<<i->second<<endl;
虽然这适用于矢量,但由于没有为地图实现”运算符,因此它会导致地图出错.实现结果的一种方法是:
- 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;
有没有其他有效的方法来实现这一点?
解决方法
它没有效率,但可能更容易阅读
- for (auto i = std::next(table.begin(),2); i != table.end(); i++)