发现最大元件的位置元件、位置、发现、最大

2023-09-11 02:02:19 作者:奶糖味小可爱

是否有一个标准的函数返回值的数组?

Is there a standard function that returns the position(not value) of the max element of an array of values?

例如:

说,我有一个这样的数组:

say i have an array like this:

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

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

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

I want a function that returns the integer of 3 that tells me that sampleArray[3] is the largest value in the array.

推荐答案

在STL, 的std :: max_element 提供了迭代器(可用于获取与指数的 的std ::距离 ,如果​​你真的想要的话)。

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