どうも、ちょげ(@chogetarou)です。
Vectorの要素を大きい順にソートする方法を紹介します。
方法

Vectorの要素を降順に並び替えるには、std::sort()を使います。
まず、algorithmをインクルードします。
#include <algorithm>
次に、std::sort()を呼び出します。
std::sort()の第1引数にVectorのイテレータの先頭、第2引数にVectorのイテレータの末尾を指定します。
そして、std::sort()の第3引数にgreater<>()を指定します。
//myVector=対象のVector
std::sort(myVector.begin(), myVector.end(), greater<>());
上記のstd::sort()は、Vectorの要素を降順に並び替えます。
使用例
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void){
vector<int> nums = { 11, 2, 8, 20, 7, 4 };
sort(nums.begin(), nums.end(), greater<>());
for(int item: nums) {
cout << item << endl;
}
return 0;
}
出力:
20
11
8
7
4
2
コメント