c++ set unordered_set区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/haluoluo211/article/details/82468061

c++ stdsetunordered_set区别和mapunordered_map区别类似:

  1. set基于红黑树实现,红黑树具有自动排序的功能,因此map内部所有的数据,在任何时候,都是有序的。

  2. unordered_set基于哈希表,数据插入和查找的时间复杂度很低,几乎是常数时间,而代价是消耗比较多的内存,无自动排序功能。底层实现上,使用一个下标范围比较大的数组来存储元素,形成很多的桶,利用hash函数对key进行映射到不同区域进行保存。

更详细的区别,如下图:

这里写图片描述

stackoverflow .

示例:

set:
Input : 1, 8, 2, 5, 3, 9
Output : 1, 2, 3, 5, 8, 9

Unordered_set:
Input : 1, 8, 2, 5, 3, 9
Output : 9 3 1 8 2 5 (顺序依赖于 hash function)

下面在给出一个以vector<int>key的示例,对比下setunordered_set

  set<vector<int>> 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

因为vector 重载了 operator<,因此可以作为setkey.

但是如果直接使用unordered_set<vector<int>> s;则报错,因为vector没有hash 函数,需要自己定义一个,可以定义一个类型下面这样的hash函数:

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;
    }
};

接下来这样使用:

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

或者模板特化struct hash<std::vector<int>>

namespace std {
    template<>
    struct hash<std::vector<int>> {
        size_t operator()(const 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;
        }
    };
}

// usage example
void test_unordered_set(){
    unordered_set<std::vector<int>> s;
    s.insert({1, 2});
    s.insert({1, 3});
    s.insert({1, 2});
    for(const auto& vec:s)
        cout<<vec<<endl;
    //    1 3
    //    1 2

    std::hash<int> hasher;
    cout<<"hasher(99): "<<hasher(99)<<" ,hasher(77): "<<hasher(77)<<endl;
    // hasher(99): 99 ,hasher(77): 77
}

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3ez16n7773c48

参考:
https://www.geeksforgeeks.org/set-vs-unordered_set-c-stl/
https://stackoverflow.com/a/52203931/6329006
https://stackoverflow.com/a/29855973/6329006

STL map, hash_map , unordered_map区别、对比

猜你喜欢

转载自blog.csdn.net/haluoluo211/article/details/82468061