我正在迭代 C++ 映射。假设我想获取 map 中除前 2 个之外的键。键在 map 中排序。因此我想到了使用这样的东西:
map<int, int> table;
for( auto i = table.begin()+2; i != table.end(); i++ )
cout<<i->first<<"\t"<<i->second<<endl;
虽然这适用于 vector ,但由于未为 map 实现“+”运算符,它会在 map 上引发错误。实现结果的一种方法是:
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++)
关于c++ - 如何迭代 C++ 映射中的一组特定键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32365131/