我们可以擦除基于范围的for循环在c ++ 11中的项目 [英] Can we erase the items in range-based for loop in c++11
本文介绍了我们可以擦除基于范围的for循环在c ++ 11中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除C ++ 11标准容器中
v
下的所有项目是我的代码:
I would like to erase all the items less than v
in C++11 standard container set
, here is my code:
void delete_less_than(set<int> & ss, int const v) {
for (auto item: ss) {
if (item < v) {
ss.erase(ss.find(item));
} else break;
}
}
代码是否正常工作?我似乎在我的电脑上(g ++ 4.7.3),但循环无限上一些在线法官,我提交我的代码。
Will the code work properly? I seems okay on my computer (g++ 4.7.3), but loops infinitely on some online judge where I submit my code.
推荐答案
这不是基于范围的循环。不要使用它;使用正常的代替
循环。基于范围的版本只有在您想对容器中的每个元素执行某些操作时,不改变容器。
That's not what the range-based loop is for. Don't use it; use a normal for
loop instead. The range-based version is only if you want to do something with every element in the container, without mutating the container.
for (auto it = ss.begin(); it != ss.end(); )
{
if (*it < v) { ss.erase(it++); }
else { ++it; }
}
更简单:
ss.erase(ss.begin(), ss.lower_bound(v));
这篇关于我们可以擦除基于范围的for循环在c ++ 11中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文