溫馨提示×

如何在C++中自定義set排序規則

c++
小樊
101
2024-11-30 12:22:38
欄目: 編程語言

在C++中,你可以通過創建一個自定義的比較函數或比較類來定義std::set的排序規則

方法1:使用比較函數

#include <iostream>
#include <set>
#include <vector>

// 自定義比較函數
bool my_compare(int a, int b) {
    return a < b;
}

int main() {
    // 使用自定義比較函數創建set
    std::set<int, decltype(&my_compare)> my_set(my_compare);

    // 向set中添加元素
    my_set.insert(5);
    my_set.insert(3);
    my_set.insert(8);
    my_set.insert(1);

    // 輸出set中的元素(按自定義排序規則)
    for (const auto& elem : my_set) {
        std::cout << elem << " ";
    }

    return 0;
}

方法2:使用比較類

#include <iostream>
#include <set>
#include <vector>

// 自定義比較類
struct MyCompare {
    bool operator()(int a, int b) const {
        return a < b;
    }
};

int main() {
    // 使用自定義比較類創建set
    std::set<int, MyCompare> my_set(MyCompare());

    // 向set中添加元素
    my_set.insert(5);
    my_set.insert(3);
    my_set.insert(8);
    my_set.insert(1);

    // 輸出set中的元素(按自定義排序規則)
    for (const auto& elem : my_set) {
        std::cout << elem << " ";
    }

    return 0;
}

在這兩個示例中,我們都定義了一個自定義排序規則,使得std::set中的元素按升序排列。你可以根據需要修改比較函數或比較類,以實現不同的排序規則。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女