我有一个元素向量,我可以使用非常昂贵的函数从每个元素计算单个数字。我想要映射到这些数字中最小的元素。我知道如何做到这一点在C++ 03:*C++中的高效Argmin 11
Foo get_lowest(const std::vector<Foo> &foos) {
double lowest_so_far = std::numeric_limits<double>::max();
std::vector<Foo>::iterator best;
for(std::vector<Foo>::iterator i = foos.begin(); i != foos.end(); i++) {
const double curr_val = i->bar();
if(curr_val < lowest_so_far) {
best = i;
lowest_so_far = curr_val
}
}
return *i;
}
我也可以做到这一点使用std::min_element
,除了做事(调用Foo::bar
并返回从<
一个布尔值)的简单的方式调用Foo::bar
更多的时间比我上面发布的代码。我可以预先计算每个值,然后使用std::min_element
,但该代码比上面的代码更复杂。
在融入本土,有人(肖恩父母,感谢SChepurin!)说,一个良好的风格指南现代C++是为了避免“原始循环”。有没有更多的C++ 11习惯做我想做的事情?
*我刚才输入到窗口此,我甚至没有尝试编译它。
通常情况下,“原始数组”与[''](http://en.cppreference.com/w/cpp/header/algorithm)函数相反。 –
Drop
@Drop对不起,我不明白。那么原始数组呢? – anjruu
我不确定您通过“调用Foo :: bar”的次数超过我发布的代码的意思......“。您的代码基本上实现了与http://www.cplusplus.com/reference/algorithm/min_element/ –