一文搞懂C++中max()与max_element()的区别

max与max_element简析

max(a,b),返回a,b两者之间的较大值
max_element(r, r+6),返回数组r中[0, 6)之间的最大值的迭代器
使用max_element返回的值减去数组头地址即为该最大值在数组的序号
min 和 min_element的区别同上,看到下面的例子你就会明白了

程序代码

#include <iostream>
#include <algorithm>
using namespace std;
int main(void)
{
	int a[6] = {5, 3, 2, 6, 1, 4};
	int b = a[0];
	int c = a[1];
	cout<<max(b, c)<<" "<<min(b,c)<<endl; //输出为5 3
	cout<<max_element(a, a+6) - a<<endl;// 输出为3 下标
	cout<<*max_element(a, a+6)<<endl;//输出为 6 
	cout<<min_element(a, a+6) - a<<endl;// 输出为4 下标
	cout<<*min_element(a, a+6)<<endl;	 //输出为1 
	return 0; 
}

max_element是用来来查询最大值所在的第一个位置。

max_element有两种写法:
第一种是从头迭代器到尾迭代器用自己写的方法去比较,
第二种是直接用它自带的头迭代器到尾迭代器的比较大小。

自定义比较方法可直接写在函数里

// 查找freq中最多的执行次数(存在value中)
int maxExec = max_element(freq.begin(), freq.end(), 
						  [](const auto& u, const auto& v) {return u.second < v.second;})->second;

也可以写在外面

#include <algorithm>
#include <iostream>

using namespace std;
struct structs 
{
	bool operator() (int i, int j) 
	{
		return i<j; 
	}
} structs;
//此处也可以直接用  bool bools(int i, int j) { return i<j; }

void main()
{
	int ints[] = { 3,5,7,2,7,6,4 };
//方法一
cout << "方法一最大值地址是" << max_element(ints, ints + 7, structs) << endl;
cout << "方法一最大值的位置是"  << *max_element(ints, ints + 7, structs ) << endl;
//方法二
cout << "方法二最大值地址是" << max_element(ints, ints + 7) << endl;
cout << "方法二最大值的位置是"  << *max_element(ints, ints + 7) << endl;
//如果不加*获取的是他的地址
int pos = *max_element(ints, ints + 7);
	int i;
	for (i = 0; i < 10; i++)
	{
		if (ints[i] == pos)
		{
			break;
		}
	}
	cout << "最大值的位置是" << i + 1 << endl;
}

结果如下:
在这里插入图片描述

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值