C++ STL set自定义比较函数
来源:互联网 发布:天梯金融 淘宝 编辑:程序博客网 时间:2024/06/10 03:08
C++ STL 容器很多都可以自定义比较函数,给容器调用,对其中的子项做排序。下面是一个小例子:
- #include <set>
- #include <string>
- #include <iostream>
- using namespace std;
- class CTest {
- public:
- CTest() { num = 0; str = ""; }
- CTest(int _num, string _str) { num = _num; str = _str; }
- string str;
- int num;
- };
- class CTestCmp {
- public:
- bool operator() (const CTest& lc, const CTest& rc) {
- //return !!(lc.num < rc.num);
- return !!(lc.str < rc.str);
- }
- };
- typedef set<CTest, CTestCmp> CTestSet;
- void OutputCTestSet(const CTestSet &_set) {
- cout << "Set [" << endl;
- for(CTestSet::iterator it = _set.begin(); it != _set.end(); ++it) {
- cout << "str:" << it->str << ", num:" << it->num << endl;
- }
- cout << "]" << endl;
- }
- int main(int argc, char* argv[])
- {
- CTestSet _set;
- _set.insert(CTest(2, "hello"));
- _set.insert(CTest(1, "world"));
- _set.insert(CTest(3, "blowing"));
- OutputCTestSet(_set);
- return 0;
- }
ln 15定义比较函数类,ln 23申明使用了这个比较类的set类型,main()函数中给该类型的对象放入三个子项,然后依次输出。
放开ln 19,屏蔽ln 18,输出:(按str属性升序排列)
- Set [
- str:blowing, num:3
- str:hello, num:2
- str:world, num:1
- ]
放开ln 18,屏蔽ln 19,输出:(按num属性升序排列)
- Map [
- str:world, num:1
- str:hello, num:2
- str:blowing, num:3
- ]
注意,ln 18或ln 19,使用 (left < right) 的比较方式,排序方式就是升序,即从小到大;反之,如果用 (left > right),将降序、从大到小排序。
0 1
- C++ STL set自定义比较函数
- C++ STL set自定义比较函数
- STL中sort、priority_queue、map、set的自定义比较函数
- STL中sort、priority_queue、map、set的自定义比较函数
- set自定义比较函数
- 自定义set比较函数
- STL 自定义比较函数
- STL set重载比较函数
- STL:set中使用自定义比较操作
- std::set自定义比较函数
- std::set自定义比较函数
- STL学习(二)set容器学习(二)-自定义比较函数
- STL中set、map的比较函数
- 自定义std::set比较函数的例子
- map及set中自定义比较函数
- 自定义set<T>的比较函数
- std::set、自定义类型与比较函数
- set集合容器自定义比较函数
- 51单片机中EA对于RTX51的作用
- Java线程:线程的调度-合并
- 原码, 反码, 补码 详解
- 浅谈我的iOS开发学习之路
- ny96 (n-1)数
- C++ STL set自定义比较函数
- C#以像素坐标点转以自定义坐标点
- [Leetcode] 18. 4Sum
- Can drag webview to move window in cococa?
- Java线程:线程的调度-守护线程
- Java 选择
- [Leetcode] 19. Remove Nth Node From End of List
- 快速排序的优化
- android应用性能优化注意点