zoukankan      html  css  js  c++  java
  • c++ set unordered_set区别

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

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

    set使用时设置:

    1. 我们需要有序数据(不同的元素)。
    2. 我们必须打印/访问数据(按排序顺序)。
    3. 我们需要元素的前身/后继者。

    在以下情况下使用unordered_set:

    1. 我们需要保留一组不同的元素,不需要排序。
    2. 我们需要单个元素访问,即没有遍历。

    例子:

    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更复杂。

  • 相关阅读:
    TextView-setCompondDrawables用法
    android 相对布局RelativeLayout中的一些属性的使用和实例
    登录时旋转等待效果
    使用slidingmeu_actionbarsherlock_lib的问题和The hierarchy of the type MainActivity is inconsistent
    ActionBarSherlock SlidingMenu整合,解决SlidingMenu example的getSupportActionBar()方法不能用问题
    String,StringBuffer和StringBuilder的区别
    File.separator使用
    Android常用异步任务执行方法
    adb server is out of date. killing...
    adb shell root
  • 原文地址:https://www.cnblogs.com/Jawen/p/10821702.html
Copyright © 2011-2022 走看看