C++ 查找最大元素的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2953491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the position of the max element
提问by Faken
Is there a standard function that returns the position(not value) of the max element of an array of values?
是否有标准函数返回值数组的最大元素的位置(不是值)?
For example:
例如:
Suppose I have an array like this:
假设我有一个这样的数组:
sampleArray = [1, 5, 2, 9, 4, 6, 3]
I want a function that returns the integer of 3 that tells me that sampleArray[3]
is the largest value in the array.
我想要一个函数,它返回 3 的整数,告诉我这sampleArray[3]
是数组中的最大值。
回答by Stephen
In the STL, std::max_element
provides the iterator (which can be used to get index with std::distance
, if you really want it).
在 STL 中,std::max_element
提供迭代器(std::distance
如果您真的需要,可以使用它来获取索引)。
int main(int argc, char** argv) {
int A[4] = {0, 2, 3, 1};
const int N = sizeof(A) / sizeof(int);
cout << "Index of max element: "
<< distance(A, max_element(A, A + N))
<< endl;
return 0;
}
回答by Alex
Or, written in one line:
或者,写在一行中:
std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));
回答by rashedcs
You can use max_element()
function to find the position of the max element.
您可以使用max_element()
函数来查找最大元素的位置。
int main()
{
int num, arr[10];
int x, y, a, b;
cin >> num;
for (int i = 0; i < num; i++)
{
cin >> arr[i];
}
cout << "Max element Index: " << max_element(arr, arr + num) - arr;
return 0;
}
回答by avakar
std::max_element
takes two iterators delimiting a sequence and returns an iterator pointing to the maximal element in that sequence. You can additionally pass a predicate to the function that defines the ordering of elements.
std::max_element
接受两个迭代器来分隔一个序列,并返回一个指向该序列中最大元素的迭代器。您还可以将谓词传递给定义元素顺序的函数。
回答by Uri
STL has a max_elements function. Here is an example: http://www.cplusplus.com/reference/algorithm/max_element/
STL 有一个 max_elements 函数。这是一个例子:http: //www.cplusplus.com/reference/algorithm/max_element/