2017-07-27 130 views
3

我想查找長矢量的最小值和最大值。下面的代碼有效,但我需要遍歷向量兩次。查找長矢量的最小值和最大值

我可以使用老式的循環,但我不知道是否有一個優雅的(c + + 11,標準)的方式做到這一點。

#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 


} 
+3

[一個很好的參考](http://en.cppreference.com/w/cpp/algorithm)總是很方便。 –

回答

6

你的意思是像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返回第一大元素,而minmax_element返回最後一個最大元素。例如。

1 2 1 2 
^^
    A B 

A是由您的解決方案中,並B由礦發現。 (這是爲了穩定; Alex Stepanov got the definition of max wrong in the original STL。)