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