关于 equal_func 未排序 set/map

about equal_func of unodered set/map

#include <string>
#include <unordered_set>

using namespace std;

class EQ {
public:
    bool operator()(const string& a, const string& b) const {
        bool temp{ a.size() < b.size() };
        const string& shorter{ temp ? a : b };
        const string& longer{ temp ? b : a };
        return equal(shorter.begin(), shorter.end()
            , longer.begin(), next(longer.begin(), distance(shorter.begin(), shorter.end())));
    }
};

int main(){
    unordered_set<string, hash<string>, EQ> set;
}

我觉得EQ就是每次进位都会调用的函数,检查key存在与否。但是那个 EQ 并不要求每个 set.emplace()。如何更改将在安置中调用的 compare-equality-of-keys 的功能?

unordered_set 使用桶来存储值。一个桶可能包含一个或多个对象。用于存储对象的存储桶基于散列函数 returns.

的值

在 lookub 期间(无论是插入还是检查,如果一个对象已经是集合的一部分)unordered_set 首先根据哈希确定桶,然后使用 equals 函数检查是否相等那个桶里的每一个物体。如果该桶中没有对象,则无需对等号进行检查。

这就是为什么在插入或查找时可能会或可能不会进行比较。这也是为什么您需要确保 2 个相同的对象具有相同的哈希值。