C++ sort関数:基本と応用【ソート徹底解説】

C++のsort関数は、コンテナ内の要素をソートするために使用されます。sort関数を使用するには、ヘッダーファイルを含める必要があり、コンテナ内の要素は比較操作をサポートしている必要があります。

sort関数の基本的な使い方を以下に示します:

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6};

    // 对vec中的元素进行升序排序
    std::sort(vec.begin(), vec.end());

    // 输出排序后的结果
    for (int num : vec) {
        std::cout << num << " ";
    }

    return 0;
}

上記の例では、vectorコンテナ内の要素を昇順にソートするためにsort関数を使用しました。sort関数は2つのパラメータを受け取ります。1つ目のパラメータはソートする要素の範囲の開始位置であり、2つ目のパラメータはソートする要素の範囲の終了位置です。

自己のタイプで要素をソートする場合、比較関数を提供する必要があります。これはラムダ式を使用するか、比較演算子をオーバーロードすることで実現できます。例えば、カスタムのStudent構造体をソートする場合、次のようにsort関数を使用できます:

#include <algorithm>
#include <vector>

struct Student {
    std::string name;
    int score;
};

int main() {
    std::vector<Student> students = {{"Alice", 85}, {"Bob", 90}, {"Charlie", 78}};

    // 对students中的元素按照score进行升序排序
    std::sort(students.begin(), students.end(), [](const Student& a, const Student& b) {
        return a.score < b.score;
    });

    // 输出排序后的结果
    for (const Student& student : students) {
        std::cout << student.name << " " << student.score << std::endl;
    }

    return 0;
}

上記の例では、lambda式を使用して、Student構造体のscoreを昇順でソートする比較関数を定義しました。

bannerAds