做教案找资料有哪些网站,外包服务有哪些,网站推广方法100种,网站做兼容处理怎么设置C学习笔记---025 C之unordered_set和unordered_map的模拟实现1、unordered_set的模拟实现2、unordered_map的模拟实现 C之unordered_set和unordered_map的模拟实现
前言#xff1a; 前面篇章学习了C对unordered_set和unordered_map的认识和应用#xff0c;接下来继续学习学习笔记---025 C之unordered_set和unordered_map的模拟实现1、unordered_set的模拟实现2、unordered_map的模拟实现 C之unordered_set和unordered_map的模拟实现
前言 前面篇章学习了C对unordered_set和unordered_map的认识和应用接下来继续学习C的unordered_set和unordered_map模拟实现等知识。 /知识点汇总/
1、unordered_set的模拟实现
#define _CRT_SECURE_NO_WARNINGS 1#include HashBucket.hnamespace bit1
{templateclass K, class Hash HashFuncK//class Hash HashFuncK修改参数在这里传入class unordered_set{struct SetKeyOfT{const K operator()(const K key){return key;}};public://迭代器typedef typename HashTableK,const K, SetKeyOfT, Hash::Iterator iterator;typedef typename HashTableK, const K, SetKeyOfT, Hash::const_Iterator const_iterator;iterator begin(){return _ht.Begin();}iterator end(){return _ht.End();}const_iterator begin() const{return _ht.Begin();}const_iterator end() const{return _ht.End();//这里报错是因为End()中的返回值this指针问题}pairiterator, 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://HashTableK, V _ht;HashTableK,const K, SetKeyOfT, Hash _ht;//const};void test_unordered_set(){unordered_setint s;s.insert(31);s.insert(11);s.insert(5);s.insert(15);s.insert(25);unordered_setint::iterator it s.begin();while (it ! s.end()){//*it 1;//set是不能被修改的需要const修饰cout *it ;it;}cout endl;for (auto e : s){cout e ;}cout endl;}//const迭代器void Func(const unordered_setint s){unordered_setint::iterator it s.begin();while (it ! s.end()){//*it 1;cout *it ;it;}cout endl;}
}2、unordered_map的模拟实现
#define _CRT_SECURE_NO_WARNINGS 1#include HashBucket.hnamespace bit1
{templateclass K, class V,class Hash HashFuncKclass unordered_map{struct MapKeyOfT{const K operator()(const pairK, V kv){return kv.first;}};public:typedef typename HashTableK, pairconst K, V, MapKeyOfT, Hash::Iterator iterator;iterator begin(){return _ht.Begin();}iterator end(){return _ht.End();}V operator[](const K key){pairiterator, bool ret insert(make_pair(key, V()));return ret.first-second;//报错发现-还没有写}// 21:15pairiterator, bool insert(const pairK, V kv){return _ht.Insert(kv);}private:HashTableK, pairconst K, V, MapKeyOfT, Hash _ht;};void test_unordered_map(){string arr[] { 苹果, 西瓜, 苹果, 西瓜, 苹果, 苹果, 西瓜,苹果, 香蕉, 苹果, 香蕉,苹果,草莓, 苹果,草莓 };unordered_mapstring, int countMap;for (auto e : arr){countMap[e];}unordered_mapstring, int::iterator it countMap.begin();while (it ! countMap.end()){//it-first x; // key不能修改it-second 1; // value可以修改cout it-first : it-second endl;it;}cout endl;for (auto kv : countMap){cout kv.first : kv.second endl;}cout endl;}
}