c++

如何实现 C++ Set 的自动排序

小樊
86
2024-08-09 01:08:39
栏目: 编程语言

C++中的Set数据结构是有序的,并且默认使用升序排序。如果你想要自定义排序规则,可以通过传入自定义的比较函数来实现。

#include <iostream>
#include <set>

// 自定义比较函数
struct CustomCompare {
    bool operator() (int a, int b) const {
        // 根据自定义的比较规则进行排序
        return a > b;
    }
};

int main() {
    // 使用自定义的比较函数
    std::set<int, CustomCompare> mySet = {1, 5, 3, 2, 4};

    // 遍历输出
    for (int num : mySet) {
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

在上面的例子中,我们定义了一个自定义比较函数CustomCompare,并将其作为第二个模板参数传入std::set<int, CustomCompare>中。这样就可以实现按照自定义的排序规则对Set进行排序。

如果不提供自定义比较函数,则Set会默认使用元素的operator<进行排序。

0
看了该问题的人还看了