我想找到长向量的最小值和最大值。以下代码有效,但是我需要遍历向量两次。
我可以使用老式的for循环,但是我想知道是否有一种优雅的方法(c ++ 11,std)。
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
vector<double> C;
// code to insert values in C not shown here
const double cLower = *min_element(C.begin(), C.end());
const double cUpper = *max_element(C.begin(), C.end());
// code using cLower and cUpper
}
你是说喜欢std::minmax_element
吗?
auto mm = std::minmax_element(std::begin(c), std::end(c));
const double cLower = *mm.first;
const double cUpper = *mm.second;
请注意,这假定范围不为空(与现有解决方案一样),否则迭代器的取消引用为Undefined Behavior。
还要注意,这与您的解决方案不太一样,因为它max_element
返回第一个最大的元素,并minmax_element
返回最后一个最大的元素。例如
1 2 1 2
^ ^
A B
A
您的解决方案可以找到哪里,我的也可以找到哪里B
。(这是出于稳定性的原因;Alex Stepanovmax
在原始STL中得到了错误的定义。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句