如何在c ++映射中迭代一组特定的键?

Niv*_*tha 6 c++ dictionary stl c++11

我正在迭代C++地图.假设我想获取除第一个之外的地图中存在的键.键在地图中排序.因此我想到使用这样的东西:

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

虽然这适用于矢量,但由于没有为地图实现"+"运算符,因此会引发地图错误.实现结果的一种方法是:

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;
Run Code Online (Sandbox Code Playgroud)

有没有其他有效的方法来实现这一点?

use*_*267 8

它没有效率,但可能更容易阅读

for (auto i = std::next(table.begin(), 2); i != table.end(); i++)
Run Code Online (Sandbox Code Playgroud)