查找最大元素的位置 [英] Finding the position of the maximum element

查看:30
本文介绍了查找最大元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

例如:

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

Suppose I have an array like this:

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::distance,如果你真的想要的话.

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

这篇关于查找最大元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆