C ++数组中的Max [英] Max In a C++ Array
问题描述
我正在尝试通过使用算法库/标头中的max函数在用户制作的数组中找到最大"元素.
I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
我已经在cplusplus参考站点上进行了一些研究,但是我只看到了如何使用max函数比较两个元素.相反,我试图使用函数"max"显示最大数量,而不必进行"for"循环来找到它.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
例如:
数组:array[]={0,1,2,3,5000,5,6,7,8,9}
最高值:5000
我编写了这段代码,但是它给了我很多错误,这可能是问题所在?
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}
推荐答案
max_element
是您需要的功能.它将迭代器返回给定范围内的max元素.您可以像这样使用它:
max_element
is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
在这里您可以找到有关此功能的更多信息: http://en.cppreference. com/w/cpp/algorithm/max_element
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element
这篇关于C ++数组中的Max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!