gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:33:22 25 4
gpt4 key购买 nike

我有以下内容

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 start = 0 和 end = 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;

关于c++ - 如何返回索引位置而不是值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com