2016-10-02 81 views
-2

如果下面的代碼返回至載體中的最小值索引:指數對最大值和最小值的矢量

std::min_element(prices.begin(), prices.end()) - prices.begin(); 

那麼,爲什麼不將此代碼矢量返回最大值的指數?

std::max_element(prices.begin(), prices.end()) - prices.begin(); 

編輯:例子向量。

vector<int> prices{30, 20, 18, 15, 50} 

謝謝。

+0

請包括在你的問題實際代碼,作爲[MCVE],而不是的幻想代碼。 '矢量價格{30,20,18,15,50}'不是有效的C++代碼。當糾正爲「std :: vector 價格{30,20,18,15,50};」時,這按預期工作。 –

+0

@Sam Varshavchik,冷靜下來,那是真正的代碼。 '#include ' '使用std :: vector;'在頂部。是的,我忘了包括''部分。 @ juanchopanza,謝謝你的編輯。 – Tahmid

+0

正如我所寫,這符合預期。 'std :: cout <<(std :: max_element(prices.begin(),prices.end()) - prices.begin())<< std :: endl;'產生'4',這是正確的。 –

回答

0

該代碼工作正常,並按預期。 第一個元素的索引是零

#include <iostream> 
#include <vector> 
#include <algorithm> 

using namespace std; 

int main() 
{ 
    vector<int> prices{30, 20, 18, 15, 50}; 
    int min_index = std::min_element(prices.begin(), prices.end()) - prices.begin(); 
    int max_index = std::max_element(prices.begin(), prices.end()) - prices.begin(); 
    std::cout<<"Minimum position: "<<min_index+1<<endl; 
    std::cout<<"Minimum position: "<<max_index+1<<endl; 
} 

的 輸出: 最低位置:4

最低位置:5