2016-10-02 84 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