写在前面
C++中,对于一个vector
容器,如果要获取其中的最大值及对应的位置索引,需要怎么做呢,本文将一探究竟1。
案例演示
用一个例子来对该需求进行演示,代码如下:
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
int main()
{
std::vector<std::string> num{ "0", "1", "2", "3", "4",
"5", "6", "7", "8", "9" };
//std::cout << num.at(2) << std::endl; // 2
//std::cout << num[2] << std::endl; // 2
std::vector<float> score{ 0.111, 0.034, 0.102, 0.002, 0.939, 0.069 }; // 在创建的同时指定初始值以及元素个数
/*
for (auto i = score.begin(); i < score.end(); i++) {
std::cout << *i << "*"; // 输出 0.111*0.034*0.102*0.002*0.939*0.069*
}
*/
#if 1
// 查找整个容器中的最大值
std::vector<float>::iterator biggest = std::max_element(std::begin(score), std::end(score));
std::cout << "Max element is " << *biggest << ", at position " << std::distance(std::begin(score), biggest) << std::endl; // Max element is 0.939, at position 4
// 分别查找容器的前两个元素中的最大值,以及容器剩下元素中的最大值
std::vector<float>::iterator max_front = std::max_element(std::begin(score), (std::begin(score) + 2));
std::cout << "Max first two element is " << *max_front << ", at position " << std::distance(std::begin(score), max_front) << std::endl; // Max first two element is 0.111, at position 0
auto front_idx = std::distance(std::begin(score), max_front);
std::cout << front_idx << std::endl; // 0
std::vector<float>::iterator max_back = std::max_element((std::begin(score) + 2), std::end(score));
std::cout << "Max last other element is " << *max_back << ", at position " << std::distance((std::begin(score) + 2), max_back) << std::endl; // Max last other element is 0.939, at position 2
#endif
return 0;
}
输出为:
Max element is 0.939, at position 4
Max first two element is 0.634, at position 1
1
Max last other element is 0.939, at position 2
请按任意键继续. . .
写到这里,差不多本文也就要结束了。如果我的这篇文章帮助到了你,那我也会感到很高兴,一个人能走多远,在于与谁同行。