for_each 避免原始循环

Kat*_*e44 1 c++ stl

我正在尝试使用 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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

汽车是矢量类型

nr 是我作为参数得到的 int

这个 for 循环真的只做一些有效性,整个函数做别的事情所以我的问题是,有没有一种很好的方法可以用一些 STL 算法替换这个循环?for_each 似乎是一个尝试,但我不知道如何使用它,因为我无法真正为这个特定的有效性创建另一个函数。

我看到了在 for_each 中使用 lambda 的方法,但我也不知道该怎么做。

谢谢

And*_*dyG 5

如果您使用 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");
}
Run Code Online (Sandbox Code Playgroud)

我假设cars包含类型的对象Car