我正在尝试使用 STL 算法 (C++11) 重写我的一些代码,但我陷入了“无原始循环”规则。
我的一个函数中有这段代码:
for (size_t i = 0; i < cars->size(); i++) {
if (cars->at(i).getNumber() == nr) {
throw RepositoryException ("Product with the same number already exists");
}
}
汽车是 vector 类型
nr 是我作为参数获取的 int
这个 for 循环实际上只做了一些有效性,整个函数做了其他事情所以我的问题是,有没有一个很好的方法用一些 STL 算法替换这个循环? for_each 似乎是一个尝试,但我无法弄清楚如何使用它,因为我不能真正为这个特定的有效性创建另一个函数。
我看到了在 for_each 中使用 lambda 的方法,但我也不确定该怎么做。
谢谢
最佳答案
如果您使用 C++11 进行编译,我推荐 std::any_of
:
#include <algorithm>
//...
if (std::any_of(std::begin(*cars),std::end(*cars),
[&nr](const Car& c){return c.getNumber() == nr;})
{
throw RepositoryException ("Product with the same number already exists");
}
我假设 cars
包含 Car
类型的对象
关于c++ - for_each 避免原始循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29996983/