1、代码示例: 关注注释
// 模板为stl库提供
template <class T>
struct less {
bool operator() (const T& x, const T& y) const {return x<y;}
};
#include <map>
#include <utility>
#include <iostream>
using namespace std;
// 自定义key值
struct mytest {
int a_;
int b_;
mytest() = default;
mytest(int a, int b) : a_(a), b_(b) {}
};
// 实现key值得小于运算符
bool operator<(const mytest& mytest1, const mytest& mytest2)
{
return std::tie(mytest1.a_,mytest1.b_) < std::tie(mytest2.a_,mytest2.b_);
}
int main()
{
// map中自定义排序需要实现小于判断:可以通过函数指针形式或函数对象形式
// 通过框架提供得std::less<>模板类完成函数对象的创建
std::map<mytest, int, std::less<mytest>> my;
my.insert(std::make_pair<mytest, int>(mytest(5,1), 3));
my.insert(std::make_pair<mytest, int>(mytest(1,2), 3));
if (my.find(mytest(5,1)) != my.end()) {
cout << "GET IT" << endl;
}
return 0;
}
注:find的实现通过A不小于B,且B不小于A来实现。
参考资料:
1、std::map::map
2、STL自定义排序函数:sort()函数;priority_queue,set,map等容器排序函数