C++ vector 最大值和最大值的位置

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main(){
    vector<int> a = { 2,4,6,7,1,10,24,8,9,6,3,2 };
    vector<int>::iterator maxPosition = max_element(a.begin(), a.end());
    cout << *maxPosition << " at the postion of " << maxPosition - a.begin() <<endl;
    return 0;
}

  • 輸出
    24 at the postion of 6

值得注意的是這裏的迭代器"vector::iterator"也可以改爲auto,它能夠自動識別對應的類型

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章