C ++中发现最大的元件的(最大)指数以阵列 [英] C++ finding the (largest) index of the largest element in an array
问题描述
我有值的阵列和用于在一个阵列寻找最大元素的索引的技术。
I have an array of values and a technique for finding the 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
However if there's multiple instances of the largest value, for e.g. {3,1,3,4,4,3,2} it only returns the smallest index (in this case 3), whereas I'd like it to return the largest index, in this case 4.
我能想到这样做会创建一个新的阵列中,等同于arrayOfValues,但反向的,然后应用上述方法的唯一途径。
The only way I can think of doing it would be to create a new array which is identical to 'arrayOfValues' but in reverse, and then apply the above method.
是否有这样做的一个简单的方法,将避免建立新的阵列?也许通过操纵上面这段code的?
Is there a simpler way of doing it that would avoid creating a new array? Perhaps by manipulating the above piece of code?
推荐答案
在for循环if语句添加。喜欢的东西...
In a for loop add an if statement. Something like...
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
}
这篇关于C ++中发现最大的元件的(最大)指数以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!