类内部重构比较函数
#include <iostream>
#include <map>
class mypair {
public:
int first;
bool second;
mypair(int a, bool b) : first(a), second(b) {};
bool operator< (const mypair &b) const {
return first > b.first;
};
};
int main()
{
std::map<mypair, int> newmap;
mypair a(1, false);
newmap[a] = 666;
std::cout << newmap[a];
}
函数比较器或lambda
#include <iostream>
#include <map>
class mypair {
public:
int first;
bool second;
mypair(int a, bool b) : first(a), second(b) {};
};
bool com (const mypair &a,const mypair &b) {
return a.first > b.first;
};
int main()
{
std::map<mypair, int,decltype(com)*> newmap(com);
mypair a(1, false);
newmap[a] = 666;
std::cout << newmap[a];
}
int main()
{
auto com = [&](const mypair &a, const mypair &b)->bool {return a.first > b.first; };
std::map<mypair, int,decltype(com)> newmap(com);
mypair a(1, false);
newmap[a] = 666;
std::cout << newmap[a];
}
函数对象结构体
#include <iostream>
#include <map>
class mypair {
public:
int first;
bool second;
mypair(int a, bool b) : first(a), second(b) {};
};
class compar {
public:
bool operator() (const mypair &a,const mypair &b) const {
return a.first > b.first;
};
};
int main()
{
std::map<mypair, int, compar> newmap;
mypair a(1, false);
newmap[a] = 666;
std::cout << newmap[a];
}