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.h"
namespace bit1
{
template<class K, class Hash = HashFunc<K>>//class Hash = HashFunc<K>修改参数在这里传入
class unordered_set
{
struct SetKeyOfT
{
const K& operator()(const K& key)
{
return key;
}
};
public:
//迭代器
typedef typename HashTable<K,const K, SetKeyOfT, Hash>::Iterator iterator;
typedef typename HashTable<K, 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指针问题
}
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:
//HashTable<K, V> _ht;
HashTable<K,const K, SetKeyOfT, Hash> _ht;//+const
};
void test_unordered_set()
{
unordered_set<int> s;
s.insert(31);
s.insert(11);
s.insert(5);
s.insert(15);
s.insert(25);
unordered_set<int>::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_set<int>& s)
{
unordered_set<int>::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.h"
namespace bit1
{
template<class K, class V,class Hash = HashFunc<K>>
class unordered_map
{
struct MapKeyOfT
{
const K& operator()(const pair<K, V>& kv)
{
return kv.first;
}
};
public:
typedef typename HashTable<K, pair<const K, V>, MapKeyOfT, Hash>::Iterator iterator;
iterator begin()
{
return _ht.Begin();
}
iterator end()
{
return _ht.End();
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = insert(make_pair(key, V()));
return ret.first->second;//报错发现->还没有写
}
// 21:15
pair<iterator, bool> insert(const pair<K, V>& kv)
{
return _ht.Insert(kv);
}
private:
HashTable<K, pair<const K, V>, MapKeyOfT, Hash> _ht;
};
void test_unordered_map()
{
string arr[] = { "苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜",
"苹果", "香蕉", "苹果", "香蕉","苹果","草莓", "苹果","草莓" };
unordered_map<string, int> countMap;
for (auto& e : arr)
{
countMap[e]++;
}
unordered_map<string, 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;
}
}