c++ std中set与unordered_set区别和map与unordered_map区别类似:
set基于红黑树实现,红黑树具有自动排序的功能,因此map内部所有的数据,在任何时候,都是有序的。unordered_set基于哈希表,数据插入和查找的时间复杂度很低,几乎是常数时间,而代价是消耗比较多的内存,无自动排序功能。底层实现上,使用一个下标范围比较大的数组来存储元素,形成很多的桶,利用hash函数对key进行映射到不同区域进行保存。set使用时设置:
在以下情况下使用unordered_set:
例子:
set:
输入:1,8,2,5,3,9
输出:1,2,3,5,8,9
Unordered_set:
输入:1,8,2,5,3,9
输出:9 3 1 8 2 5(也许这个顺序,受哈希函数的影响)
主要区别:
注意:(在某些情况下set更方便)例如使用vectoras键
set<vector<int>> s;
s.insert({1, 2});
s.insert({1, 3});
s.insert({1, 2});
for(const auto& vec:s)
    cout<<vec<<endl;   // I have override << for vector
// 1 2
// 1 3 
之所以vector<int>可以作为关键set因为vector覆盖operator<。
但是如果你使用unordered_set<vector<int>>你必须创建一个哈希函数vector<int>,因为vector没有哈希函数,所以你必须定义一个像:
struct VectorHash {
    size_t operator()(const std::vector<int>& v) const {
        std::hash<int> hasher;
        size_t seed = 0;
        for (int i : v) {
            seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
        }
        return seed;
    }
};
vector<vector<int>> two(){
    //unordered_set<vector<int>> s; // error vector<int> doesn‘t  have hash function
    unordered_set<vector<int>, VectorHash> s;
    s.insert({1, 2});
    s.insert({1, 3});
    s.insert({1, 2});
    for(const auto& vec:s)
        cout<<vec<<endl;
    // 1 2
    // 1 3
}
你可以看到在某些情况下unordered_set更复杂。
原文:https://www.cnblogs.com/Jawen/p/10821702.html