查找长向量的最小值和最大值

Find minimum and maximum of a long vector

我想求一个长向量的最小值和最大值。以下代码有效,但我需要遍历向量两次。

我可以使用老式的 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 Behaviour

另请注意,这与您的解决方案并不完全相同,因为 max_element returns 是第一个最大的元素,minmax_element returns 是最后一个最大的元素。例如

1 2 1 2
  ^   ^
  A   B

其中 A 是由您的解决方案找到的,而 B 是由我的解决方案找到的。 (这是出于稳定性的原因;Alex Stepanov got the definition of max wrong in the original STL。)