首页 > 其他分享 >STL-unordered_map,unordered_set模拟实现

STL-unordered_map,unordered_set模拟实现

时间:2024-02-27 22:58:07浏览次数:20  
标签:map set const iterator key return unordered

unordered_set

#pragma once

#include"28hashtable_container.h"

namespace test
{
    //template < 
    // class Key,                        // unordered_set::key_type/value_type
    //    class Hash = hash<Key>,           // unordered_set::hasher
    //    class Pred = equal_to<Key>,       // unordered_set::key_equal
    //    class Alloc = allocator<Key>      // unordered_set::allocator_type
    //> class unordered_set;

    template<class K, class Hash = HashBucket::HashFunc<K>>
    class unordered_set
    {
    private:
         struct setKeyOfT
        {
            const K& operator()(const K& key)
            {
                return key;
            }
        };
    public:
        typedef typename HashBucket::HashTable<K, K, setKeyOfT, Hash>::const_iterator iterator;
        typedef typename HashBucket::HashTable<K, K, setKeyOfT, Hash>::const_iterator const_iterator;

    public:
        iterator begin()
        {
            return _ht.begin();
        }

        iterator end()
        {
            return _ht.end();
        }
        const_iterator begin()const
        {
            return _ht.begin();
        }

        const_iterator end()const
        {
            return _ht.end();
        }

        pair<iterator,bool> insert(const K& key)
        {
            return _ht.insert(key);
        }

        iterator find(const K& key)
        {
            return _ht.find(key);
        }

        bool erase(const K& key)
        {
            return _ht.erase(key);
        }


    private:
        HashBucket::HashTable<K, K, setKeyOfT , Hash> _ht;

    }; //unordered_set_end;

    void test_My_unordered_set1()
    {
        int a[] = { 3, 33, 2, 13, 5, 12, 1002 };

        test::unordered_set<int> s;
        //s.insert(1);
        
        for (auto i : a)
        {
            s.insert(i);
        }
        s.insert(54);
        s.insert(107);
        
        s.erase(33);

        test::unordered_set<int>::iterator it = s.begin();
        while (it!=s.end())
        {
            cout << *it << endl;
            ++it;
        }

    }


}

unordered_map

#pragma once

#include"28hashtable_container.h"
#include"1Date.h"//测试用



namespace test
{
    //template < class Key,                                    // unordered_map::key_type
    //    class T,                                      // unordered_map::mapped_type
    //    class Hash = hash<Key>,                       // unordered_map::hasher      //用于支持取模的仿函数
    //    class Pred = equal_to<Key>,                   // unordered_map::key_equal   //用于支持==重载的仿函数
    //    class Alloc = allocator< pair<const Key, T> >  // unordered_map::allocator_type
    //> class unordered_map;

    template<class K,class V,class Hash = HashBucket::HashFunc<K>>
    class unordered_map
    {

    private:
        struct mapKeyOfT
        {
            const K& operator()(const pair<const K, V>& kv)
            {
                return kv.first;
            }
        };

    public:
        typedef typename HashBucket::HashTable<K, pair<const K, V>, mapKeyOfT, Hash>::iterator iterator;
        typedef typename HashBucket::HashTable<K, pair<const K, V>, mapKeyOfT, Hash>::const_iterator const_iterator;

    public:
        
        iterator begin()
        {
            return _ht.begin();
        }

        iterator end()
        {
            return _ht.end();
        }
        const_iterator begin()const
        {
            return _ht.begin();
        }

        const_iterator end()const
        {
            return _ht.end();
        }

        
        pair<iterator,bool> insert(const pair<K, V> kv)
        {
            return _ht.insert(kv);
        }

        V& operator[](const K& key)
        {
            pair<iterator,bool> ret = insert(make_pair(key, V()));
            return ret.first->second; //模拟的是指针,ret.first是iterator,iterator->可以直接访问到node的成员
        }

    private:
        HashBucket::HashTable<K, pair<const K, V>, mapKeyOfT, Hash> _ht;

    }; //unordered_map_end

    void test_My_unordered_map1()
    {
        unordered_map<int, int> m;
        m.insert(make_pair(1, 1));
        m.insert(make_pair(3, 3));
        m.insert(make_pair(2, 2));

        //unordered_map<int, int>::const_iterator it = m.begin(); //测试没问题
        unordered_map<int, int>::iterator it = m.begin();
        while (it != m.end())
        {
            //it->first = 1;
            //it->second = 1;

            cout << it->first << ":" << ++it->second << endl;
            ++it;
        }
        cout << endl;
    }

    void test_My_unordered_map2()
    {
        std::string arr[] = { "西瓜", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉", "梨" };
        unordered_map<std::string, int> countMap;
        for (auto& e : arr)
        {
            countMap[e]++;
        }

        for (auto& kv : countMap)
        {
            cout << kv.first << ":" << kv.second << endl;
        }
    }


    struct HashDate
    {
        size_t operator()(const Date& d)
        {
            size_t ret = 0;
            ret += d._year;
            ret *= 31;
            ret += d._month;
            ret *= 31;
            ret += d._day;
            ret *= 31;
            return ret;
        }
    };

    void test_My_unordered_map3()
    {

       // 自定义类型作map,set的key需要支持比较大小(需要重载<) ,只需要重载一个 '<' 或 '>' 就可以比较大小 ,
        //自定义类型作unordered的key需要满足1.要有可以取模的对象 2.支持比较是否相等,hashtable需要比较key(需要重载==)
        /**
         * stl::如果作为哈希key的自定义类型不支持等于,stl的哈希map支持传仿函数 class Pred = equal_to<Key>用于自己适配
         * 
         */

        Date d1(2023, 3, 13);
        Date d2(2023, 3, 13);
        Date d3(2023, 3, 12);
        Date d4(2023, 3, 11);
        Date d5(2023, 3, 12);
        Date d6(2023, 3, 13);

        Date a[] = { d1,d2,d3,d4,d5 ,d6};

        unordered_map<Date, int, HashDate> m;

        for (auto& e : a)
        {
            ++m[e];
        }

        for (auto& kv : m)
        {
            cout << kv.first << ":"<<kv.second << endl;
        }

        
    }

}

 

标签:map,set,const,iterator,key,return,unordered
From: https://www.cnblogs.com/DSCL-ing/p/18038615

相关文章

  • STL-unordered_hashtable模拟实现
    #pragmaonce#include<vector>#include<string>#include<iostream>usingstd::cout;usingstd::endl;usingstd::pair;usingstd::make_pair;namespaceHashBucket{template<classT>structHashNode{HashNode......
  • STL-RBT_map,set模拟实现
    set#include"26RBT_container.h"namespacetest{//set通过普通迭代器使用const迭代器实现限制key不能被修改template<classK>classset{private:structsetKeyOfT//命名?返回RBT的类型T接收的set的key{constK&......
  • STL-bitset模拟实现
    #include<time.h>#include<string>#include<vector>#include<iostream>usingstd::cout;usingstd::endl;usingstd::string;namespacetest{/**位图概念*所谓位图,就是用每一位来存放某种状态,适用于海量数据,数据无重复的场景。通常是用来判断某个数据存不存在的。......
  • Qt QVector和vector以及QMap和map的遍历性能对比
    使用Qt中的容器给C++开发带来很大的便利,而且QVector和QMap等容器扩展的一些成员函数也是很方便的。但是Qt的这些容器和STL库的容器比,效率到底怎么样?我就写了几个简单的遍历的例子,测试了QVector、vector等容器的那些方法效率更高。测试环境:系统:windows10编译器:MingGWmingw......
  • Qt QVector、QList、QSet和QMap:性能与用途比较
    Qt提供了多种容器类,用于存储和管理数据。其中,QVector、QList、QSet和QMap是最常用的几种。这些容器类在性能和用途方面存在一些差异,选择合适的容器对于提高应用程序的效率和正确性至关重要。下面我们将从以下几个方面对这四种容器进行比较:1.存储方式QVector:动态数组,元素在......
  • Characterizing Graph Datasets for Node Classification Homophily-Heterophily Dich
    目录概符号说明Popularhomophilymeasures理想的准则现有的metrics的分析PlatonovO.,KuznedelevD.,BabenkoA.andProkhorenkovaL.Characterizinggraphdatasetsfornodeclassification:homophily-heterophilydichotomyandbeyond.NIPS,2023.概阐述合理的......
  • 扩展运算符...+map+filter 在嵌套对象数组中的使用
    参考文档:使用基于嵌套值的数组过滤对象数组:https://segmentfault.com/q/1010000042989861js扩展运算符(...)的用法 :https://www.cnblogs.com/caihongmin/p/16395573.html对象的扩展运算符:https://blog.csdn.net/weixin_42265852/article/details/88739525Vue判断对象中......
  • List转Map
    //以userid为主,重复数据不获取,不会抛出异常Map<Long,UserLoginLog>longDateMap=userLoginLogList.stream().collect(Collectors.toMap(UserLoginLog::getUserId,Function.identity(),(key1,key2)->key1));//业务逻辑if(longDateMap.containsKey(listVo.getUserI......
  • unipp实现map地图轨迹,轨迹长度,标点,连线功能
    效果图 一、pages.json文件中加入{"path":"pages/map/mapd","style":{"navigationBarTitleText":"地图","app-plus":{......
  • Python中字典setdefault()方法和append()的配合使用
    1.setdefault()方法语法dict.setdefault(key,default=None)说明:如果字典中包含给定的键值,那么返回该键对应的值。否则,则返回给定的默认值。Syntax:dict.setdefault(key,default_value)Parameters:Ittakestwoparameters:key–Keytobesearchedinthedictionar......