C++ Vector 最大 最小值 索引 位置

C++ Vector 最大 最小值 索引 位置

使用STL的Vector时,利用函数 max_element,min_element,distance可以获取Vector中最大、最小值的值和位置索引:

参考:http://stackoverflow.com/questions/2953491/finding-the-position-of-the-max-element

代码:

#include 
#include 
#include 

int main()
{
    std::vector v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    std::vector::iterator biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest<< " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}


输出:

Max element is 5 at position 4
min element is 1 at position 0




你可能感兴趣的:(兴趣杂集)