#include <iostream>
#include <unordered_set>
#include <string>
namespace uset {
typedef struct PeopleInfo {
std::string name;
int age;
} PInfo, *PInfo_ptr;
typedef bool(*info_com)(const PInfo&, const PInfo&);
// std::function<bool(const PInfo&, const PInfo&)> info_com;
bool info_compare(const PInfo& left, const PInfo& right) {
return left.age > right.age;
}
struct PeopleInfoCompare {
bool operator()(const PInfo& left, const PInfo& right) const {
return left.age > right.age;
}
};
} // end of namespace uset
namespace std {
template <>
struct hash<uset::PInfo> {
size_t operator()(const uset::PInfo& self) const {
return std::hash<std::string>()(self.name) + std::hash<int>()(self.age);
}
};
} // end of namespace std
int main()
{
// std::hash<uset::PInfo> 类型, std::hash<uset::PInfo>()可调用对象
std::unordered_set<uset::PInfo, std::hash<uset::PInfo>, uset::info_com> a(2, std::hash<uset::PInfo>(), &uset::info_compare);
uset::PInfo obj1({"xiaoming", 18});
a.insert(obj1);
a.insert({"xiaohuang", 19});
for (const auto& key : a) {
std::cout << key.age << std::endl;
}
std::cout << "aaaa" << std::endl;
std::unordered_set<uset::PInfo, std::hash<uset::PInfo>, uset::PeopleInfoCompare> b;
b.insert({"xiaoming1", 18});
b.insert({"xiaohuang1", 19});
for (const auto& key : b) {
std::cout << key.age << std::endl;
}
return 0;
}
结果:
19
18
aaaa
19
18