我是靠谱客的博主 魔幻星月,这篇文章主要介绍c++ stl set 有序性,现在分享给大家,希望可以做个参考。

stl 中的set 是有序容器,可以通过传入自定义比较器函数对象的方式,设定想要使用的比较方法。

使用迭代器遍历set的时候,遍历的顺序就是set 中比较器定义的顺序。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
set<int> s; // 插入的时候按照从大到小的顺序插入 for (int i = 10; i > 0; i--) { s.insert(i); } set<int>::iterator it; // 遍历的时候的输出是从小到大 for (it = s.begin(); it != s.end(); ++it) { cout << *it ; }

可以通过传入比较器函数对象的形式,更改set排序方式

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 从大到小排序的比较器函数对象 struct Compartor { bool operator()(const int lhs,const int rhs) const { return rhs < lhs; } }; // 声明使用自定义比较器的set set<int,Compartor> s; // 按照从小到大的顺序插入 for (int i = 0; i < 10; i++) { s.insert(i); } set<int>::iterator it; // 输出的顺序的作用是从大到小 for (it = s.begin(); it != s.end(); ++it) { cout << *it ; }

stl 中set 有序的性质可以应用到同时需要过滤重复和排序的场景。

最后

以上就是魔幻星月最近收集整理的关于c++ stl set 有序性的全部内容,更多相关c++内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(71)

评论列表共有 0 条评论

立即
投稿
返回
顶部