max_element()获取vector容器中的最大值


写在前面

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
请按任意键继续. . .

写到这里,差不多本文也就要结束了。如果我的这篇文章帮助到了你,那我也会感到很高兴,一个人能走多远,在于与谁同行


参考文章


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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值