温馨提示×

C++ set函数与排序函数的结合使用

c++
小樊
81
2024-09-10 20:03:29
栏目: 编程语言

在 C++ 中,set 是一种关联容器,它包含一组唯一的元素,并按照特定的顺序进行存储。默认情况下,set 会按照升序对元素进行排序。你可以通过自定义比较函数来改变排序方式。

set 容器提供了一些有用的成员函数,如 insert()erase()find() 等,用于操作元素。这些函数可以与排序函数结合使用,以实现更复杂的功能。

下面是一个示例,展示了如何使用 set 容器和排序函数:

#include<iostream>
#include <set>
#include<algorithm>

// 自定义比较函数,用于降序排序
struct CompareDesc {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

int main() {
    // 创建一个降序排序的 set 容器
    std::set<int, CompareDesc> my_set;

    // 向 set 中插入元素
    my_set.insert(5);
    my_set.insert(3);
    my_set.insert(1);
    my_set.insert(4);
    my_set.insert(2);

    // 输出 set 中的元素
    for (int x : my_set) {
        std::cout << x << " ";
    }
    std::cout<< std::endl;

    // 使用排序函数对 set 进行升序排序
    std::vector<int> sorted_vec(my_set.begin(), my_set.end());
    std::sort(sorted_vec.begin(), sorted_vec.end());

    // 输出排序后的元素
    for (int x : sorted_vec) {
        std::cout << x << " ";
    }
    std::cout<< std::endl;

    return 0;
}

在这个示例中,我们首先创建了一个降序排序的 set 容器,然后向其中插入了一些元素。接着,我们将 set 中的元素复制到一个 vector 中,并使用 std::sort() 函数对其进行升序排序。最后,我们输出了排序后的元素。

0