2011-06-18 28 views
0

有人可以幫助我找到最大值包含的向量的位置。我正在使用visual C++。最大值包含的向量的位置

std::vector<double> array; 

比方說:

array = {19.4 , 45.0 ,12.9 ,59.3 , 2.8 ,18.0} 

的最大值爲59.3。我想填充它的位置。

max_location = 3; 

有沒有什麼辦法得到它......?請幫幫我。

回答

0

既然是作業,我不會發布完整的解決方案,只是一個想法。看看std::max_element(例如,here)。它返回一個迭代器,如果它不等於你的array.end(),你可以得到它與array.begin()之間的距離,這將是你正在尋找的索引。

0

好的,我們來考慮一下。你想要逐個瀏覽這個向量並找到最大值;你想跟蹤價值的指數。這裏有一些僞代碼:

index = 0 
for each value in the array from 0 to end 
    if this is the highest value you've seen so far 
     save value 
     save index of value 

print index 

你怎麼能在C++中做到這些?