C++ max_element()的使用

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

max_element有两种写法,第一种是从头迭代器到尾迭代器用自己写的方法去比较,
第二种是直接用它自带的头迭代器到尾迭代器的比较大小。
在这里插入图片描述
代码如下:

#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;
}

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

  • 32
    点赞
  • 100
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值