パープルハット

※当サイトではGoogleアドセンス広告を利用しています

C++ vectorの並び替え(ソート、逆順)

昇順・降順ソート(std::sort)

#include <algorithm>

をすることでソートを行う関数std::sortを使用できるようになります(公式ドキュメント:sort - cpprefjp C++日本語リファレンス)。
並び替えたいvectorを「v」とすると、昇順・降順ソートは次の処理で実装できます。

昇順 std::sort(v.begin(), v.end())
降順 std::sort(v.begin(), v.end(), std::greater<>)


サンプルコード

#include <iostream>
#include <vector>
#include <algorithm>

int main() {

    //宣言
    std::vector<int> v{ 3, 4, 2, 10 };

    //昇順ソート
    std::sort(v.begin(), v.end());

    //降順ソート
    //std::sort(v.begin(), v.end(), std::greater<>());

    //中身を列挙
    std::cout << "v = { ";
    for (const auto& a: v) {
        std::cout << a << ", ";
    }
    std::cout << "}" << std::endl;

    return 0;
}

実行結果

v = { 2, 3, 4, 10, }



逆順(std::reverse)

「2, 0, 2, 4」という配列を逆順の「4, 2, 0, 2」にするにはstd::reverse関数を使います(参考:reverse - cpprefjp C++日本語リファレンス)
reverseの例

サンプルコード

#include <iostream>
#include <vector>
#include <algorithm>

int main() {

    //宣言
    std::vector<int> v{ 3, 4, 2, 10 };

    //反転
    std::reverse(v.begin(), v.end());

    //中身を列挙
    std::cout << "v = { ";
    for (const auto& a : v) {
        std::cout << a << ", ";
    }
    std::cout << "}" << std::endl;

    return 0;
}

実行結果

v = { 10, 2, 4, 3, }