[C++]Vectorを降順に並び替えるには?

C++

どうも、ちょげ(@chogetarou)です。

Vectorの要素を大きい順にソートする方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

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の要素を降順に並び替えます。

sort()の第3引数に、「第1引数 > 第2引数」を返す関数を指定して、降順に並び替える方法もあります。

sort(myVector.begin(), myVector.end(), [](auto const &i, auto const &j) { return i > j; });

使用例

#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

コメント

タイトルとURLをコピーしました