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

C++

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

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

スポンサーリンク

方法

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

Vectorの要素を昇順に並び替えるには、std::sort()を使います。

まず、algorithmをインクルードします。

#include <algorithm>

次に、std::sort()を呼び出します。

std::sort()の第1引数にVectorのイテレータの先頭、第2引数にVectorのイテレータの末尾を指定します。

//myVec=対象のVector
sort(myVec.begin(), myVec.end());

上記の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());
    
    for(int item: nums) {
        cout << item << endl;
    }
    
    return 0;
}
出力:
2
4
7
8
11
20

コメント

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