繁体   English   中英

C ++查找数组中最大元素的(最大)索引

[英]C++ finding the (largest) index of the largest element in an array

我有一个值数组和一种用于查找数组中最大元素的索引的技术。

value = distance(arrayOfValues, max_element(arrayOfValues, arrayOfValues + N));

但是,如果存在多个最大值的实例,例如{3,1,3,4,4,3,2},它只会返回最小的索引(在这种情况下为3),而我希望它返回最大的索引索引,在这种情况下为4。

我能想到的唯一方法是创建一个与'arrayOfValues'相同但相反的新数组,然后应用上述方法。

有没有一种更简单的方法可以避免创建新数组? 也许通过操纵上面的代码?

您可以提供一个自定义比较器来比较地址:

const int index =
    std::distance(std::begin(arrayOfValues),
        std::max_element(std::begin(arrayOfValues), std::end(arrayOfValues),
        [](const int& lhs, const int& rhs) {
            return std::make_tuple(lhs, &lhs)
            < std::make_tuple(rhs, &rhs);
        }
        ));

现场例子

在您的范围内使用反向迭代器。

您将end传递给反向迭代器构造函数以获取反向开始,然后开始获取反向结束。

template<class It>
std::reverse_iterator<It> rit(It i){return {i};}

template<class C>
struct backwards_t {
  C c;
  auto end() {
    using std::begin;
    return rit(begin(c));
  }
  auto begin() {
    using std::end;
    return rit(end(c));
  }
};
template<class C>
backwards_t<C> backwards(C&&c){return {std::forward<C>(c)};}

是C ++ 14的一种实现方法。

auto yarra = backwards(array);
auto it = std::max_element(yarra.begin(), yarra.end());

这也使您可以在for(:)循环中backwards调用backwards迭代。

在for循环中添加if语句。 就像是...

int indexToReturn = 0;
int indexValue = 0;
int newValue = 0;
for (int i = 0; i < arrayCount; i++) {
    newValue = arrayOfValues[i];
    if (newValue >= indexValue) {
        indexToReturn = i;
        indexValue = newValue;
    }
// At the end of this loop the value you want is indexToReturn
}

您可能有这样的事情:

int maxIdx = 0;  
for(int i = 0; i < n; ++i)
  if(a[maxIdx] > a[i])
    maxIdx = i;

return maxIdx;

您只需要在if语句中添加一个字符:

if(a[maxIdx] >= a[i])
  maxIdx = i;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM