使用STL求取数组中的最大值和最小值

2025-10-18 03:20:48

1、使用VS2013新建一个BoostTest控制台工程,如下图:

使用STL求取数组中的最大值和最小值

2、在BoostTest.cpp输入以下代码:

#include <iostream>

#include <vector>

#include <algorithm>

/*

使用STL求取数组的最大值和最小值

*/

void TestStlGetMaxMin(void)

{

 // 定义数组

    double a[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };

    std::vector<double> arr(a, a + 10);

    std::vector<double>::iterator max = std::max_element(std::begin(arr), std::end(arr));

    //  vector<double>::iterator max=max_element(arr.begin(),arr.end());// 或者也可以这样表示,计算max 

    std::cout << "数组最大值是: " << *max << " ,位置是 " << std::distance(std::begin(arr), max) << std::endl;

    //输出值一定是带*,输出*max,表示解引用  

    auto min = std::min_element(std::begin(arr), std::end(arr));

    std::cout << "数组最小值是: " << *min << " ,位置是 " << std::distance(std::begin(arr), min) << std::endl;

}

int _tmain(int argc, _TCHAR* argv[])

{

    TestStlGetMaxMin();

    getchar();

    return 0;

}

3、编译执行程序,运行结果如下图:

使用STL求取数组中的最大值和最小值

4、假如数组中存在两个相同的最大值或最小值,程序会如何输出呢?我们测试一下,把数组a变为,

double a[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0 };

可以看到程序输出的是第一个最大值和最小值。

运行结果如下图:

使用STL求取数组中的最大值和最小值

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢