如何返回索引位置而不是值?

时间:2015-03-07 04:55:05

标签: c++ return

我有以下

int index = 0;

for (int i = start; i < end; ++i)
{
    cout << spot.at(i) << ' '; // prints 190 2 94
    if (spot.at(i) > spot.at(index)) // finds the greatest value which is 190 so gives back 0 bc spot.at(0) has the highest value
    {
        index = i;
        cout << index;
    }
}
return index; 

因此,当我编译时,我得到190而不是索引,这是0.如果我没有把返回最大值我得到0但我需要返回具有最大值的索引,所以我必须包括“return”。它工作正常,但随后它保持波动,所以有时它有效,但它没有。现在我再次尝试使用这些值129 55 161 67 107 187 164 102 72 135 197 197 start = 0和end = 11但是它一直给我197而不是10的索引。如果我打印索引它确实给了我10但是当我返回索引时,它什么也没给我。仍然不太确定什么是错的,谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

int max_index = 0;
for (int i = start; i < end; ++i)
{
    cout << spot.at(i) << ' '; // prints 190 2 94
    if (spot.at(i) > spot.at(max_index)) // find the greatest value
    {
        max_index = i;
    }
}
return max_index;

答案 1 :(得分:2)

您希望跟踪max值以及max值所在的索引。然后,当您找到新的max时,您同时更新了maxmaxIndex

int max = spot.at(0);
int maxIndex = 0;
for (int i = start; i < end; ++i)
{
    cout << spot.at(i) << ' '; // prints 190 2 94

    if (spot.at(i) > max) // find the greatest value
    {
        max = spot.at(i);
        maxIndex = i;
    }
}
return maxIndex;
相关问题