C++ Vector容器查找最大值,最小值以及相应的索引位置

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

实现代码如下:

#include "pch.h"
#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
	std::vector<double> v{ 9.9, 12.0, 38.0, 46.0, 195.0, 431.0, 27.0, 93.0, 4.0, 0.8 };      //定义double型的Vector并初始化
	std::vector<double>::iterator biggest = std::max_element(std::begin(v), std::end(v));    //获取最大值指针
	int nMaxIndex = std::distance(std::begin(v), biggest);                                   //获取最大值索引
	std::cout << "Max element is " << *biggest << " at position " << nMaxIndex << std::endl; //命令行打印
	auto smallest = std::min_element(std::begin(v), std::end(v));                            //获取最小值指针
	int nMinIndex = std::distance(std::begin(v), smallest);                                  //获取最小值索引
	std::cout << "min element is " << *smallest << " at position " << nMinIndex << std::endl;//命令行打印
}

输出:

Max element is 431 at position 5
min element is 0.8 at position 9

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐