转载自:
https://blog.youkuaiyun.com/yasi_xi/article/details/8701220
注意:
- 比较函数
bool operator() (const CTest& lc, const CTest& rc)
后不添加const时在gcc 4.8.5 c++11可以通过编译,在目前最新的gcc 11.0.1中不能通过编译,严谨起见,添加了const. 原因估计是gcc 11.0.1中默认编译参数-std 大于c++11。
代码:
#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) const {
//return !!(lc.num < rc.num);
return lc.str < rc.str;
}
};
typedef set<CTest, CTestCmp> CTestSet;
void OutputCTestSet(const CTestSet &_set) {
cout << "Set [" << endl;
for(auto it = _set.begin(); it != _set.end(); ++it) {
cout << "str:" << it->str << ", num:" << it->num << endl;
}
cout << "]" << endl;
}
int main()
{
CTestSet _set;
_set.insert(CTest(2, "hello"));
_set.insert(CTest(1, "world"));
_set.insert(CTest(3, "blowing"));
OutputCTestSet(_set);
return 0;
}
执行结果:
Set [
str:blowing, num:3
str:hello, num:2
str:world, num:1
]