目录
unordered系列关联式容器
之前讲解在C++98中STL提供了底层为红黑树结构的一系列关联式容器,在查询时效率可达到 l o g 2 N log_2N log2N,即最差情况下需要比较红黑树的高度次,当树中的节点非常多时,查询效率也不理想。最好的查询是,进行很少的比较次数就能够将元素找到,因此在C++11中,STL又提供了4个unordered系列的关联式容器,这四个容器与红黑树结构的关联式容器使用方式基本类似,只是其底层结构不同使用哈希结构。unordered_map、unordered_set、unordered_multimap和unordered_multiset
unordered_map
- unordered_map是存储<key, value>键值对的关联式容器,其允许通过keys快速的索引到与其对应的value。
- 在unordered_map中,键值通常用于惟一地标识元素,而映射值是一个对象,其内容与此键关联。键和映射值的类型可能不同。
- 在内部,unordered_map没有对<kye, value>按照任何特定的顺序排序, 为了能在常数范围内找到key所对应的value,unordered_map将相同哈希值的键值对放在相同的桶中。
- unordered_map容器通过key访问单个元素要比map快,但它通常在遍历元素子集的范围迭代方面效率较低。
- unordered_maps实现了直接访问操作符(operator[]),它允许使用key作为参数直接访问value。
- 它的迭代器只有前向迭代器。
第三方
- 使用方式和map一样
但操作性能相比map更高:O(1)的复杂度
//使用方式和map一样
unordered_map<int, int> m;
//操作性能相比map更高:O(1)的复杂度
m.insert(make_pair(1, 1));
m[2] = 2;
- 不同在于map遍历出来的值是有序的而unordered_map遍历出的值是无序的
unordered_map只有正向迭代器,没有反向迭代器。
for (int i = 3; i < 100; ++i)
{
m[i] = i;
}
//相对于map/set,unordered_map/set只有正向迭代器
//迭代器遍历,不是有序的
unordered_map<int, int>::iterator it = m.begin();
while (it != m.end())
{
cout << it->first << " ";
}
cout << endl;
- equal_range:左闭右开的区间,查询key
由于是map,不允许Key重复,因此只输出了一个值3;如果是multimap可以有多个key值则会输出更多。
//equal_range:
auto range = m.equal_range(3);
it = range.first;
while (it != range.second)
{
cout << it->first << " ";
++it;
}
cout << endl;
哈希
unordered系列的关联式容器之所以效率比较高,是因为其底层使用了哈希结构。
哈希概念
顺序结构以及平衡树中,元素关键码与其存储位置之间没有对应的关系,因此在查找一个元素时,必须要经过关键码的多次比较。顺序查找时间复杂度为O(N),平衡树中为树的高度,即O(
l
o
g
2
N
log_2 N
log2N),搜索的效率取决于搜索过程中元素的比较次数。
理想的搜索方法:可以不经过任何比较,一次直接从表中得到要搜索的元素。
如果构造一种存储结构,通过某种函数(hashFunc)使元素的存储位置与它的关键码之间能够建立一一映射的关系,那么在查找时通过该函数可以很快找到该元素。
当向该结构中:
- 插入元素
根据待插入元素的关键码,以此函数计算出该元素的存储位置并按此位置进行存放
- 搜索元素
对元素的关键码进行同样的计算,把求得的函数值当做元素的存储位置,在结构中按此位置取元素比较,若关键码相等,则搜索成功
该方式即为哈希(散列)方法,哈希方法中使用的转换函数称为哈希(散列)函数,构造出来的结构称为哈希表(Hash Table)(或者称散列表)
哈希函数
直接定址法:
kx+b :适用于小范围数据的位置计算。如果数据范围过大会造成空间浪费。
除留余数法:
x%空间大小:通用
例如:数据集合{1,7,6,4,5,9};
哈希函数设置为:hash(key) = key % capacity; capacity为存储元素底层空间总的大小。
哈希冲突
对于两个数据元素的关键字
k
i
k_i
ki和
k
j
k_j
kj(i != j),有
k
i
k_i
ki !=
k
j
k_j
kj,但有:Hash(
k
i
k_i
ki) ==Hash(
k
j
k_j
kj),即:不同关键字通过相同哈希哈数计算出相同的哈希地址,该种现象称为哈希冲突或哈希碰撞。如上图4和14的哈希地址相同。
把具有不同关键码而具有相同哈希地址的数据元素称为“同义词”。
解决哈希冲突
闭散列:
- 线性探测
从计算的哈希位置开始,找第一个空闲的位置,存放数据。
//记录位置状态(哈希表内的数据删除相当于伪删除,因为查询数据如果查找到空余位就会停止查找,比如5,15,25,把15删掉后,查询25时走到15位置发现空余,会停止查找,因此在删除15时不能直接删除)
enum STATE
{
EXIST, //存在
DELETE, //删除
EMPTY //空
};
template <class K, class V>
struct hashNode
{
pair<k, V> _kv;
STATE _state = EMPTY;
};
//顺序表实现hash
template <class K, class V>
class HashTable
{
public:
typedef HashNode<K, V> Node;
HashTable(size_t n = 10)
:_hTable(n)
, _size(0)
{}
bool insert(const pair<K, V>& kv)
{
//0.检查容量
checkCapacity();
//1.计算哈希位置
int idx = kv.first % _hTable.size();
//2.判断key是否存在
while (_hTable[idx]._state != EMPTY)
{
//如果当前位置数据有效,且key相同,插入失败
if (_hTable[idx]._state == EXIST && kv.first == _hTable[idx]._kv.first)
{
return false;
}
//继续搜索
++idx;
if (idx == _hTable.size())
idx = 0;
}
//插入
_hTable[idx] = kv;
_hTable[idx]._state = EXIST;
++_size;
return true;
}
void checkCapacity()
{
//负载因子:<1 有效元素个数/容量大小
//负载因子越小可存储的元素就越多,可也浪费的越多,因此权衡取:0.7
if (_hTable.size() == 0 || _size * 10 / _hTable.size() >= 7)
{
//开新表
int newC = _hTable.size() == 0 ? 10 : 2 * _hTable.size();
HashTable<K, V> newHt(newC);
for (int i = 0; i < _hTable.size(); ++i)
{
//插入状态为exist的数据
if (_hTable[i]._state == EXIST)
{
newHt.insert(_hTable[i]._kv);
}
}
Swap(newHt);
}
}
void Swap(HashTable<K, V>& Ht)
{
swap(_hTable, Ht._hTable);
swap(_size, Ht._size);
}
Node* find(const K& key)
{
//计算位置
int idx = key % _hTable.size();
while (_hTable[idx]._state != EMPTY)
{
if (_hTable[idx]._state == EXIST && key == _hTable[idx]._kv.first)
{
return &_hTable[idx];
}
++idx;
if (idx == _hTable.size())
{
idx = 0;
}
}
return nullptr;
}
bool erase(const K& key)
{
Node* node = find(key);
if (node)
{
//假删除
--_size;
node->_state = DELETE;
return true;
}
return false;
}
private:
vector<Node> _hTable;
size_t _size; //有效元素的个数
};
void test()
{
HashTable<int, int> ht;
ht.insert(make_pair(1, 1));
ht.insert(make_pair(14, 14));
ht.insert(make_pair(16, 16));
ht.insert(make_pair(11, 11));
cout << ht.erase(11) << endl;
cout << ht.erase(100) << endl;
}
- 二次探测
线性探测的缺陷是产生冲突的数据堆积在一块,这与其找下一个空位置有关系,因为找空位置的方式就是挨着往后逐个去找,因此二次探测为了避免该问题,找下一个空位置的方法为: H i H_i Hi = ( H 0 H_0 H0 + i 2 i^2 i2 )% m, 或者: H i H_i Hi = ( H 0 H_0 H0 - i 2 i^2 i2 )% m。其中:i =1,2,3…, H 0 H_0 H0是通过散列函数Hash(x)对元素的关键码 key 进行计算得到的位置,m是表的大小。
与线性探测的不同在于找一个空位置的不同,线性探测一个一个找,二次探测每次找的位置是上次的二次,比如第一次找第一个位置,第二次找二个位置,第三次找第四个位置。
开散列:
开散列法又叫链地址法(开链法),首先对关键码集合用散列函数计算散列地址,具有相同地址的关键码归于同一子集合,每一个子集合称为一个桶,各个桶中的元素通过一个单链表链接起来,各链表的头结点存储在哈希表中。
底层结构哈希表–代码实现:
using namespace std;
//*************************************************************************************hash桶
//开散列
//单链表的节点
//因为要实现map和set的底层结构,因此节点里面只放value不放key
template <class V>
struct HashNode
{
V _val;
HashNode<V>* _next;
HashNode(const V& val)
:_val(val)
, _next(nullptr)
{}
};
//哈希表的前置声明
template <class K, class V, class KeyOfValue, class HashFun = HashFun<K>>
class HashTable;
//哈希表迭代器:自定义类型
//通过封装单链表的节点实现
template <class K, class V, class KeyOfValue, class HashFun = HashFun<K>>
struct HashIterator
{
typedef HashIterator<K, V, KeyOfValue, HashFun> Self;
typedef HashTable<K, V, KeyOfValue, HashFun> HT;
//成员:节点指针
typedef HashNode<V> Node;
Node* _node;
HT* _hPtr;
HashIterator(Node* node, HT* hPtr)
:_node(node)
, _hPtr(hptr)
{}
V& operator*()
{
return _node->_val;
}
V* operator->()
{
return _node->_val;
}
bool operator!=(const Self& it)
{
return _node != it._node;
}
Self& operator++()
{
if (_node->_next)
{
_node = _node->_next;
}
else
{
//查找下一个非空链表的头结点
//计算当前节点在哈希表中的位置
KeyOfValue kov;
HashFun hfun;
size_t idx = hfun(kov(_node->_val)) & _hPtr->_ht.size();
//从下一个哈希位置开始查找
++idx;
for (; idx < _hPtr->_ht.size(); ++idx)
{
if (_hPtr->_ht[idx])
{
//找到下一个非空链表
_node = _hPtr->_ht[idx];
break;
}
}
if (idx == _hPtr->_ht.size())
{
_node = nullptr;
}
}
return *this;
}
};
template <class K, class V, class KeyOfValue, class HashFun>
class HashTable
{
public:
typedef HashNode<V> Node;
typedef HashIterator<K, V, KeyOfValue, HashFun> iterator;
//把迭代器声明为友元类
template <class K, class V, class KeyOfValue, class HashFun>
friend struct HashIterator;
HashTable(int n = 10)
: _ht(n)
, _size(0)
{}
iterator begin()
{
//第一个非空链表的头结点
for (size_t i = 0; i < _ht.size(); ++i)
{
if (_ht[i])
{
return iterator(_ht[i], this);
}
}
return iterator(nullptr, this);
}
iterator end()
{
return iterator(nullptr, this);
}
bool insert(const V& val)
{
//0.检查容量
checkCapacity();
//1.计算hash位置
KeyOfValue kov;
HashFun hfun;
int idx = hfun(kov(val)) % _ht.size();
//2.查找
Node* cur = _ht[idx];
while (cur)
{
if (kov(cur->_val) == kov(val))
{
//key重复
return false;
}
cur = cur->_next;
}
//3.插入:头插
cur = new Node(val);
cur->_next = _ht[idx];
_ht[idx] = cur;
++_size;
reutrn true;
}
void checkCapacity()
{
if (_size == _ht.size())
{
//int newC = _size == 0 ? 10 : 2 * _size;
size_t newC = GetNextPrime(_ht.size());
//创建新的指针数组
vector<Node*> newHt(newC);
KeyOfValue kov;
HashFun hfun;
//遍历旧表
for (size_t i = 0; i < _ht.size(); ++i)
{
Node* cur = _ht[i];
//遍历单链表
while (cur)
{
Node* next = cur->_next;
//计算新的位置
int idx = hfun(kov(cur->_val)) & newHt.size();
//头插
cur->_next = newHt[idx];
newHt[idx] = cur;
cur = next;
}
//旧表指针置空
_ht[i] = nullptr;
}
//新表,旧表交换
swap(_ht, newHt);
}
}
private:
//指针数组
vector<Node*> _ht;
int _size;
};
template <class K>
struct HashFun
{
size_t operator()(const K& key)
{
return key;
}
};
template <>
struct HashFun<string>
{
size_t operator()(const string& key)
{
size_t hash = 0;
for (const auto& ch : key)
{
hash = hash * 131 + ch;
}
return hash;
}
};
利用哈希结构实现set:
template <class K>
class Set
{
struct SetKeyOfValue
{
const K& operator()(const K& key)
{
return key;
}
};
public:
typedef typename HashTable<K, K, SetKeyOfValue>::iterator iterator;
iterator begin()
{
return _ht.begin();
}
iterator end()
{
reutrn _ht.end();
}
pair<iterator, bool> insert(const K& key)
{
return _ht.insert(key);
}
private:
HashTable<K, K, SetKeyOfValue> _ht;
};
void test_set()
{
Set<int> s;
s.insert(1);
s.insert(2);
s.insert(3);
s.insert(4);
s.insert(41);
s.insert(42);
s.insert(11);
Set<int>::iterator it = s.begin();
while (it != s.end())
{
cout << *it << " ";
++it;
}
cout << endl;
for (const auto& e : s)
{
cout << e << " ";
}
cout << endl;
}
利用哈希结构实现map:
template <class K, class V>
class Map
{
struct MapKeyOfValue
{
const K& operator()(const pair<K, V>& val)
{
return val.first;
}
};
public:
typedef typename HashTable<K, pair<K, V>, MapKeyOfValue>::iterator iterator;
pair<iterator, bool> insert(const pair<K,V>& val)
{
return _ht.insert(val);
}
iterator begin()
{
return _ht.begin();
}
iterator end()
{
reutrn _ht.end();
}
V& operator[](const K& key)
{
pair<iterator, bool> ret = _ht.insert(make_pair(key, V()));
return ret.first->second;
}
private:
HashTable<K, pair<K, V>, MapKeyOfValue> _ht;
};
void test_map()
{
Map<int, int> m;
m.insert(make_pair(1, 1));
m[20] = 20;
m[30] = 30;
m[1] = 10;
Map<int, int>::iterator it = m.begin();
while (it != m.end())
{
//it的解引用是pair对象
cout << it->first << "-->" << it->second << endl;
++it;
}
cout << "范围for" << endl;
for (const auto& p : m)
{
cout << p.first << "-->" << p.second << endl;
}
}
哈希的应用
位图
位图概念
位图,就是用每一位来存放某种状态,适用于海量数据,数据无重复的场景。通常是用来判断某个数据存不存在的。
正常存放一个整数,需要4个字节,32位;用位图在存放一个整数的信息,只需要用一个bit位的大小,相当于正常存放的1/32。
位图实现
//位图:使用场景-->存放不重复数据的简单信息,不需要存放数据本身
//优点:节省空间,查找效率高:O(1)
class BitSet
{
public:
//位图的内存大小和数据范围有关系
BitSet(size_t range)
:_bit(range / 32 + 1)
{}
//存储信息
void set(size_t num)
{
//计算位置
//1.计算整数位置: / 32
int idx = num / 32;
//2.计算bit位置: % 32
int bitIdx = num % 32;
//把对应的bit位置置1
//按位或运算
_bit[idx] |= 1 << bitIdx;
}
//查找信息
bool find(size_t num)
{
int idx = num / 32;
int bitIdx = num % 32;
//将bitIdx高位右移到0位,与1相与
return (_bit[idx] >> bitIdx) & 1;
}
//删除信息
void reset(size_t num)
{
int idx = num / 32;
int bitIdx = num % 32;
_bit[idx] &= ~(1 << bitIdx);
}
private:
//整数数组
vector<int> _bit;
};
void test()
{
//开出512个数据位置用来记录512个数据的二值信息
BitSet bit(512);
//对以下数据的位置置1
bit.set(1);
bit.set(32);
bit.set(512);
//该值存在则返回1,不存在返回0
bool ret = bit.find(1);
ret = bit.find(3);
//将该值从位图删掉(将该位置置0)
bit.reset(32);
}
布隆过滤器
布隆过滤器概念
概率型数据结构,特点是高效地插入和查询,可以用来告诉你 “某样东西一定不存在或者可能存在”,它是用多个哈希函数,将一个数据映射到位图结构中。此种方式不仅可以提升查询效率,也可以节省大量的内存空间。
布隆过滤器实现
//m:需要的bit位大小
//n:元素个数
//k:哈希函数个数
// k = m/n * ln2
// m = k * n * 1.4
//使用场景:存放各种数据的简单信息
//概率型容器:判断存在,结果不一定正确
//一般没有删除操作:存在误删
//时间复杂度:O(k)
template < class T, class Hash1, class Hash2, class Hash3>
class BloomFilter
{
public:
BloomFilter(size_t num)
//5 ≈ 3*1.4
:_bit(5 * num)
, _bitCount(5 * num)
{}
//存储信息:使用多个bit位存储信息
void set(const T& val)
{
{
Hash1 h1;
Hash2 h2;
Hash3 h3;
int idx1 = h1(val) % _bitCount;
int idx2 = h2(val) % _bitCount;
int idx3 = h3(val) % _bitCount;
_bit.set(idx1);
_bit.set(idx2);
_bit.set(idx3);
}
}
bool test(const T& val)
{
{
Hash1 h1;
Hash2 h2;
Hash3 h3;
int idx1 = h1(val) % _bitCount;
int idx2 = h2(val) % _bitCount;
int idx3 = h3(val) % _bitCount;
if (!_bit.find(idx1))
return false;
if (!_bit.find(idx2))
return false;
if (!_bit.find(idx3))
return false;
return true; //可能存在
}
}
private:
BitSet _bit;
//bit位的个数
size_t _bitCount;
};
struct HashFun1
{
size_t operator()(const string& str)
{
size_t hash = 0;
for (const auto& ch : str)
{
hash = hash * 131 + ch;
}
return hash;
}
};
struct HashFun2
{
size_t operator()(const string& str)
{
size_t hash = 0;
for (const auto& ch : str)
{
hash = hash * 65599 + ch;
}
return hash;
}
};
struct HashFun3
{
size_t operator()(const string& str)
{
size_t hash = 0;
for (const auto& ch : str)
{
hash = hash * 1313131 + ch;
}
return hash;
}
};
void test_b()
{
BloomFilter<string, HashFun1, HashFun2, HashFun3> bf(10);
string str1 = "https://blog.csdn.net/m0_49619206?spm=1000.2115.3001.5343";
string str2 = "https://mp.csdn.net/mp_blog/creation/success/134140411";
string str3 = "https://blog.csdn.net/m0_49619206/article/details/134034481?spm=1001.2014.3001.5501";
bf.set(str1);
bf.set(str2);
bool ret = bf.test(str1);
ret = bf.test(str2);
ret = bf.test(str3);
}