簡體   English   中英

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

[英]How to return the index position and not the value?

我有以下

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。如果我不輸入return max,我將得到0,但是我需要返回具有最大值的索引,因此必須包含“ return”。 它工作正常,但隨后一直在波動,因此有時它可以工作,而其他時候卻沒有。 現在,我再次嘗試使用這些值129 55 161 67 107 187 164 102 72 135 197 197開始= 0,結束= 11,但是它一直給我197而不是10的索引。如果我打印索引,它確實給了我10,但當我返回索引時,它什么也沒有給我。 仍然不太確定出了什么問題,感謝您的幫助。

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;

你想跟蹤這兩個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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM