找到最大元素的位置

是否有一个标准函数返回值数组中最大元素的位置(而不是值) ?

例如:

假设我有一个这样的数组:

sampleArray = [1, 5, 2, 9, 4, 6, 3]

我需要一个返回整数3的函数,它告诉我 sampleArray[3]是数组中最大的值。

154707 次浏览

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.

In the STL, std::max_element provides the iterator (which can be used to get index with std::distance, if you really want it).

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

STL has a max_elements function. Here is an example: http://www.cplusplus.com/reference/algorithm/max_element/

You can use the max_element() function to find the position of the maximum element.

int main()
{
int num, arr[10];


cin >> num;


for (int i = 0; i < num; i++)
{
cin >> arr[i];
}


cout << "Max element Index: " << max_element(arr, arr + num) - arr;


return 0;
}

Or, written in one line:

std::cout << std::distance(sampleArray.begin(),std::max_element(sampleArray.begin(), sampleArray.end()));
cout<<max_element(arr.begin(), arr.end()) - arr.begin();