C++寻找数组最大值和最小值

C++里面有好多自带函数可以直接用,比如寻找数组中的最大最小值其实是有函数的,如下

#include <iostream>
using namespace std;
#include <algorithm>

int main() {
	int n;
	cin >> n;

	int *p = new int[n];
	for (int i = 0; i<n; i++)
	{
		cin >> p[i];

	}
	
	cout << (*min_element(p, p + n))<<' '<< (*max_element(p, p + n)) << endl;
	return 0;
}

需要用头文件<algorithm>,*min_element(p, p + n)就是在p~p+n范围内的最小的数,max类同。

另外还有很多常用的函数都有自带的,对于像我一样编程经验不是很多的小白节省了不少时间,

比如求和函数,要求一个数组中的元素之和,可以用函数 accumulate(),需要包括头文件 <numeric>

#include <iostream>
using namespace std;
#include <numeric>
int main() {

	int n;
	cin >> n;

	int *p = new int[n];
	for (int i = 0; i<n; i++)
	{
		cin >> p[i];

	}
	
	cout << accumulate(p, p + n, 0) << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/explorer9607/article/details/81628603
今日推荐