哈希 自定义key
自定义==等于判断函数==
- 结构体中重载==
- 仿函数 struct内重载()
自定义==哈希函数==
根据向量的每一个维度的不同,通过一定的计算,得到一个值,注意类型要用size_t来返回
struct Point { int x; int y; Point() : x(0), y(0){}; Point(int _x, int _y) : x(_x), y(_y){}; bool operator==(const Point &other) const { return this->x == other.x && this->y == other.y; } };
struct MyEqualFunc { bool operator()(const Point &v1, const Point &v2) const { return (v1.x == v2.x && v1.y == v2.y); } };
struct MyHashFunc { size_t operator()(const Point &p) const { return hash<int>()(p.x & p.y); } };
int main() { unordered_set<Point, MyHashFunc, MyEqualFunc> set1; unordered_set<Point, MyHashFunc> set2; set1.insert(Point(0, 1)); set1.insert(Point(0, 1)); set1.insert(Point(0, 1)); set1.insert(Point(2, 1)); set1.insert(Point(0, 1)); set1.insert(Point(1, 1)); set1.insert(Point(1, 2));
return 0;
|
map是STL里的一个模板类,用来存放<key, value>键值对的数据结构,它的定义如下。
template < class Key, //map::key_tpe class T, //map::mapped_type class Compare = less<Key>, class Alloc = allocator<pair<const Key, T>> > class map;
|
自定义key的方法主要是重载比较函数
- 重载自定义的结构体的< 注意重载函数的两个const
- lamda表达式 定义小于号的比较规则
- 结构体仿函数重载() map<Person, int, MyCompare> group;
- 利用std::function调用普通函数
- less函数的模板定制 略
struct Nodee { int a; Nodee(int val) { a = val; } bool operator<(const Nodee &other) const { return this->a < other.a; } };
bool MyFunCompare(const Nodee &p1, const Nodee &p2) { return (p1.a < p2.a); }
struct MyStructCompare { bool operator()(const Nodee &p1, const Nodee &p2) const { return (p1.a < p2.a); } };
int main() { Nodee a(5); Nodee b(1); Nodee c(100); auto cmp = [](Nodee a, Nodee b) { return a.a < b.a; }; map<Nodee, int, decltype(cmp)> map1(cmp); map<Nodee, int, MyStructCompare> map2; map<Nodee, int, function<bool(const Nodee &, const Nodee &)>> map3( MyFunCompare); return 0; }
|