21xrx.com
2025-03-29 20:10:29 Saturday
文章检索 我的文章 写文章
C++中set容器的默认排序方式
2023-06-28 21:47:41 深夜i     15     0
C++ set容器 排序方式

C++中的set容器是一种常见的数据结构,它可以存储不重复的元素并按照一定的顺序进行排序。但是,你有没有想过set容器默认的排序方式是什么呢?

首先,我们需要明确一点:set容器默认使用的是小于运算符(operator<)进行元素比较和排序。也就是说,如果我们存储的元素是int类型,那么set容器默认按照从小到大的顺序进行排序。

例如,下面这段代码演示了如何创建一个int类型的set容器,并且将一些数字存储在其中:

#include <iostream>
#include <set>
using namespace std;
int main()
{
  set<int> mySet;
  mySet.insert(5);
  mySet.insert(2);
  mySet.insert(8);
  mySet.insert(1);
  for (auto it = mySet.begin(); it != mySet.end(); ++it) {
    cout << *it << " ";
  }
  cout << endl;
  return 0;
}

输出结果为:1 2 5 8。

我们可以看到,set容器默认对int类型元素进行了从小到大的排序。

但是,如果我们希望按照其他的方式进行排序,该怎么办呢?这就需要我们自己定义元素比较函数,并将其作为set容器的模板参数。比如,如果我们希望按照从大到小的顺序进行排序,可以这样写:

#include <iostream>
#include <set>
using namespace std;
struct Compare {
  bool operator()(const int& a, const int& b) const
    return a > b;
  
};
int main()
{
  set<int, Compare> mySet;
  mySet.insert(5);
  mySet.insert(2);
  mySet.insert(8);
  mySet.insert(1);
  for (auto it = mySet.begin(); it != mySet.end(); ++it) {
    cout << *it << " ";
  }
  cout << endl;
  return 0;
}

这里我们定义了一个叫做Compare的结构体,其中包含了一个自定义的小于运算符。接着,在定义set容器时,将Compare作为第二个模板参数传入即可。

输出结果为:8 5 2 1。可以看到,set容器按照我们自定义的方式进行了排序。

综上所述,C++中set容器的默认排序方式是小于运算符。如果需要按照其他方式进行排序,需要定义自己的元素比较函数,并将其传入set容器的模板参数之中。

  
  

评论区

请求出错了