STL 中的 set 使用自定义比较运算符
来源:互联网 发布:ipadcad cad绘图软件 编辑:程序博客网 时间:2024/06/06 00:26
set
容器模版需要3个泛型参数,如下:
template<class T, class C, class A> class set;
第一个T
是元素类型,必选;
第二个C
指定元素比较方式,缺省为 Less<T>
, 即使用 <
符号比较;
第三个A
指定空间分配对象,一般使用默认类型。
因此:
(1) 如果第2个泛型参数你使用默认值的话,你的自定义元素类型需要重载 <
运算操作;
(2) 如果你第2个泛型参数不使用默认值的话,则比较对象必须具有 ()
操作,即:
bool operator()(const T &a, const T &b)
使用函数对象来自定义比较运算符:
#include <set> #include <iostream> using namespace std; //首先实例化comp aa; 然后aa(lhs, rhs)进行比较 struct comp { bool operator ()(const int &a, const int &b) { return a>b; } }; int main() { set<int,comp> s; s.insert(5); s.insert(9); s.insert(6); s.insert(13); s.insert(1); set<int,comp>::iterator it; for(it = s.begin(); it != s.end(); it++) cout<<*it<<" "; cout<<endl; return 0; }
输出:
13 9 6 5 1
使用重载运算符自定义比较函数
#include <iostream>#include <set>using namespace std;struct comp{ int id; bool operator <(const comp &a)const //排序并且去重复 { return id>a.id; }};set<comp> my; set<comp> ::iterator it; int main(){ for(int i=0;i<2;i++) { comp t1; t1.id = i; my.insert(t1); } for(it=my.begin();it!=my.end();it++) cout<<(*it).id<<endl; return 0;}
0 0
- STL 中的 set 使用自定义比较运算符
- STL:set中使用自定义比较操作
- C++ STL set自定义比较函数
- C++ STL set自定义比较函数
- STL中的容器使用比较(string vector list deque set map)
- STL中sort、priority_queue、map、set的自定义比较函数
- STL中sort、priority_queue、map、set的自定义比较函数
- 使用比较运算符
- C++ STL中的set如何对自定义类对象排序?
- set自定义比较函数
- 自定义set比较函数
- STL 中的SET使用方法
- STL中的set容器
- C++ STL中的set
- STL中的set容器
- STL中的set&&map
- STL中的set
- STL set重载比较函数
- 八大排序算法
- Boys_and_Girls
- GOF23设计模式之模板方法模式(方法回调)的理解与实现之经典
- java学习笔记——第5天
- JQuery小技巧
- STL 中的 set 使用自定义比较运算符
- HDU3768 Shopping(状态压缩DP+spfa)旅行商问题
- uva 679 Dropping Balls
- 虚拟机下Ubuntu修改分辨率
- exFAT硬盘写保护修复&远程登录提示到期
- 逗号运算符和逗号表达式
- Unity3d 对手柄支持的坑
- github之Bug分支
- OC---初识 OC与C的区别 小结