C++ STL set自定义比较函数
C++ STL 容器很多都可以自定义比较函数,给容器调用,对其中的子项做排序。下面是一个小例子:[cpp] viewplaincopy#include #include #include using namespace std; class CTest { public:
·
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),将降序、从大到小排序。
更多推荐
已为社区贡献4条内容
所有评论(0)