max_element、min_element用法

max_element类型是指针,指向值最大的那个元素;max_element指向值最小的那个元素。

测试如下:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
	int a[] = { 42, 13, 12, 68, 25, 6, 5, 32 };
	int len = sizeof(a) / sizeof(int);
	auto s1 = max_element(a, a + len);
	auto s2 = min_element(a, a + len);
	cout << s1 << endl;    //指向值最大的元素的地址
	cout << s2 << endl;    //指向值最小的元素的地址
	cout << *s1 << endl;   //值最大的元素
	cout << *s2 << endl;   //值最小的元素
	cout << s1 - a << endl; //值最大的元素的索引
	cout << s2 - a << endl; //值最小的元素的索引

	return 0;
}

结果如下:

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/82932163