1. 程式人生 > >求vector向量中的最大值與最小值

求vector向量中的最大值與最小值

使用STL的vector時,利用函式 max_element,min_element,distance可以獲取vector中最大、最小值的值和位置索引。

程式碼如下:

#include <algorithm>
#include <iostream>
 
int main()
{
    std::vector<double>  vec{1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
 
    std::vector<double>::iterator biggest = std::max_element(std::begin(vec), std::end(vec));
    std::cout << "Max element is " << *biggest<< " at position " << std::distance(std::begin(vec), biggest) << std::endl;
 
    auto smallest = std::min_element(std::begin(vec), std::end(vec));
    std::cout << "min element is " << *smallest<< " at position " << std::distance(std::begin(vec), smallest) << std::endl;
}
 
 
輸出:
 
Max element is 5 at position 4
min element is 1 at position 0