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

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


版权声明:本文为qq_39686486原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。