哈希表实现unordered_map

目录

哈希表

1.哈希表概念

1.1直接定址法

1.2哈希冲突

1.3负载因子

1.4哈希函数

1.4.1除法散列法/除留余数法

1.4.2乘法散列法

1.4.3全域散列法

2.处理哈希冲突

2.1开放定址法

线性探测

二次探测

开放定址法代码

2.2链地址法(哈希桶)

链地址法代码:

unordered_map

unordered_map的实现

Myunodered_map可执行代码:


哈希表

哈希(hash)⼜称散列,是⼀种组织数据的⽅式。哈希表也是一种数据结构。从译名来看,有散乱排列的意思。本质就是通过哈希 函数把关键字Key跟存储位置建⽴⼀个 映射关系 ,查找时通过这个哈希函数计算出Key存储的位置,进⾏快速查找,时间复杂度是O(1)

1.哈希表概念

1.1直接定址法

直接定址法可以开启对哈希的认知。当关键字的范围⽐较集中时,直接定址法就是⾮常简单⾼效的⽅法,⽐如⼀组关键字都在[0,99]之间, 那么我们开⼀个100个数的数组,每个关键字的值直接就是存储位置的下标,这个就是直接定址法。但是这种方法有很大的局限性,数据范围太大这种方法就不适用了
26个字母的直接定址法

class Solution {
public :
int firstUniqChar (string s) {
// 每个字⺟的ascii -'a' ascii 码作为下标映射到 count 数组,数组中存储出现的次数
int count[ 26 ] = { 0 };
// 统计次数
for ( auto ch : s)
{
count[ch- 'a' ]++;
}
for ( size_t i = 0 ; i < s. size (); ++i)
{
if (count[s[i]- 'a' ] == 1 )
return i;
}
return -1 ;
}
};

1.2哈希冲突

数据范围是[0, 9999]的N个值,我们要映射到⼀个M个空间的数组中(⼀般情况下M >= N),那么就要借助 哈希函数 (hash function)hf,关键字key被放到数组的h(key)位置,且h(key)计算出的值必须在[0, M)之间
不过问题就是,两个不同的key可能会映射到同⼀个位置去,这种问题我们叫做哈希冲突,或者哈希碰撞。理想情况是找出⼀个好的哈希函数避免冲突,但是实际场景中,冲突是不可避免的,
所以我们尽可能设计出优秀的哈希函数,减少冲突的次数,同时也要去设计出解决冲突的⽅案

上面这个实例中,19,30,52,63这几个数经过哈希函数处理,h(key)= 8,这几个数就是冲突

1.3负载因子

哈希表中已经映射存储了N个值,哈希表的⼤⼩为M,负载因子 = ,有时叫做载荷因⼦/装载因⼦等
负载因⼦越⼤,哈希冲突的概率越⾼,空间 利⽤率越⾼;负载因⼦越⼩,哈希冲突的概率越低,空间利⽤率越低

1.4哈希函数

哈希函数的作用就是在哈希表中将数据尽量的均匀分开

1.4.1除法散列法/除留余数法

除法散列法是很常用的方法,假设哈希表的⼤⼩为M,那么通过 key除以M的余数作为 映射位置的下标
除留余数法的哈希函数为:h(key) = key % M

使⽤除法散列法时,要尽量避免M为某些值,如2的幂,10的幂等
因为cpu使用的是二进制,M=时,相当于只保留了key的后x位,M的二进制的x位以外的位数并没有参与运算;自然数用的是十进制,同理,也会造成同样的问题

1.4.2乘法散列法

这个方法不是很常用,乘法散列法对哈希表⼤⼩M没有要求,他的⼤思路第⼀步:⽤关键字 K 乘上常数 A (0<A<1),并抽
取出 k*A 的⼩数部分。第⼆步:后再⽤M乘以k*A 的⼩数部分,再向下取整
h ( key ) = floor ( M × (( A × key)%1.0)),其中floor表⽰对表达式进⾏下取整,A∈(0,1)

1.4.3全域散列法

这个方法了解即可,如果存在⼀个恶意的对⼿,他针对我们提供的散列函数,特意构造出⼀个发⽣严重冲突的数据集,⽐如,让所有关键字全部落⼊同⼀个位置中。这种情况是可以存在的,只要散列函数是公开且确定的,就可以实现此攻击。解决⽅法⾃然是⻅招拆招,给散列函数增加随机性,攻击者就⽆法找出确定可以导致最坏情况的数据。这种⽅法叫做全域散列
h ab ( key ) = (( a × key + b )% P )%M, P需要选⼀个⾜够⼤的质数,a可以随机选[1,P-1]之间的
任意整数,b可以随机选[0,P-1]之间的任意整数,这些函数构成了⼀个P*(P-1)组全域散列函数组

这样就可以防止黑客等恶意攻击

2.处理哈希冲突

处理哈希冲突有两大类方法,开放定址法,链地址法

2.1开放定址法

开放定址法的哈希表的结构是vector中存放Node节点的形式

意味着一个在哈希表的vector当中,一个索引底下只能存放一个Node,其他的数据需要在他周围另找空间,所以线性探测、二次探测、双重探测出现了


在开放定址法中所有的元素都放到哈希表⾥,当⼀个关键字key⽤哈希函数计算出的位置冲突了,则按 照某种规则找到⼀个没有存储数据的位置进⾏存储,开放定址法中负载因⼦⼀定是⼩于的。这⾥的规则主要有两种: 线性探测、⼆次探测

线性探测

从发⽣冲突的位置开始,依次线性向后探测,直到寻找到下⼀个没有存储数据的位置为⽌,如果⾛
到哈希表尾,则回绕到哈希表头的位置
h ( key ) = hash 0 = key % *M,*hash0位置冲突了,则线性探测公式为:
hc ( key , i ) = hashi = ( hash 0 + i ) % M,i = {1, 2, 3, ..., M− 1}, 由于 负载因⼦⼩于1, 则最多探测M-1次,⼀定能找到⼀个存储key的位置

下⾯演⽰ {19,30,5,36,13,20,21,12} 等这⼀组值映射到M=11的表中

二次探测

从发⽣冲突的位置开始,依次左右按⼆次⽅跳跃式探测,直到寻找到下⼀个没有存储数据的位置为
⽌,如果往右⾛到哈希表尾,则回绕到哈希表头的位置;如果往左⾛到哈希表头,则回绕到哈希表
尾的位置
h ( key ) = hash 0 = key % M , hash0位置冲突了,则⼆次探测公式为:
hc ( key , i ) = hashi = ( hash 0 ± ) % Mi = {1, 2, 3, ..., }
⼆次探测当 hashi = ( hash 0 − i 2 )% M 时,当hashi<0时,需要hashi += M

下⾯演⽰ {19,30,52,63,11,22} 等这⼀组值映射到M=11的表中

开放定址法代码

其中的HashFunc是用来计算数据在哈希表中数组的索引,是哈希表里面的功能函数,并且是仿函数,还使用了模板的特化专门对string处理

并非我们所说的将数据均匀分散开的哈希函数

cpp 复制代码
namespace open_address
{
    #include<string>
    #include<vector>
    #include<algorithm>
	using namespace std;

	enum State
	{
		EXIST,
		EMPTY,
		DELETE
	};
	template<class K, class V>
	struct HashData
	{
		pair<K, V> _kv;
		State _state = EMPTY;
	};

	template<class K>
	struct HashFunc
	{
		size_t operator()(const K& key)
		{
			return (size_t)key;
		}
	};

    //模板的特化,处理string
	template<>
	struct HashFunc<string>
	{
		size_t ret = 0;
		size_t operator()(const string& key)
		{
			for (auto e : key)
			{
				ret *= 31;
				ret += e;
			}
			return ret;
		}
	};
	template<class K, class V, class Hash = HashFunc<K>>
	class HashTable
	{
	public:
		inline unsigned long __stl_next_prime(unsigned long n)
		{
			// Note: assumes long is at least 32 bits.
			static const int __stl_num_primes = 28;
			static const unsigned long __stl_prime_list[__stl_num_primes] =
			{
				53, 97, 193, 389, 769,
				1543, 3079, 6151, 12289, 24593,
				49157, 98317, 196613, 393241, 786433,
				1572869, 3145739, 6291469, 12582917, 25165843,
				50331653, 100663319, 201326611, 402653189, 805306457,
				1610612741, 3221225473, 4294967291
			};
			const unsigned long* first = __stl_prime_list;
			const unsigned long* last = __stl_prime_list +
				__stl_num_primes;
			const unsigned long* pos = lower_bound(first, last, n);
			return pos == last ? *(last - 1) : *pos;
		}
		HashTable()
		{
			_tables.resize(__stl_next_prime(0));
		}
		bool Insert(const pair<K, V>& kv)
		{
			if (Find(kv.first))
				return false;
			// 负载因⼦⼤于0.7就扩容
			if (_n * 10 / _tables.size() >= 7)
			{
				// 这⾥利⽤类似深拷⻉现代写法的思想插⼊后交换解决
				HashTable<K, V, Hash> newHT;
				newHT._tables.resize(__stl_next_prime(_tables.size() + 1));
				for (size_t i = 0; i < _tables.size(); i++)
				{
					if (_tables[i]._state == EXIST)
					{
						newHT.Insert(_tables[i]._kv);
					}
				}
				_tables.swap(newHT._tables);
			}
			Hash hash;
			size_t hash0 = hash(kv.first) % _tables.size();
			size_t hashi = hash0;
			size_t i = 1;

			while (_tables[hashi]._state == EXIST)
			{
				// 线性探测
				hashi = (hash0 + i) % _tables.size();
				// ⼆次探测就变成 +- i^2
				++i;
			}
			_tables[hashi]._kv = kv;
			_tables[hashi]._state = EXIST;
			++_n;
			return true;
		}
		HashData<K, V>* Find(const K& key)
		{
			Hash hash;
			size_t hash0 = hash(key) % _tables.size();
			size_t hashi = hash0;
			size_t i = 1;
			while (_tables[hashi]._state != EMPTY)
			{
				if (_tables[hashi]._state == EXIST
					&& _tables[hashi]._kv.first == key)
				{
					return &_tables[hashi];
				}
				// 线性探测
				hashi = (hash0 + i) % _tables.size();
				++i;
			}
			return nullptr;
		}
		bool Erase(const K& key)
		{
			HashData<K, V>* ret = Find(key);
			if (ret == nullptr)
			{
				return false;
			}
			else
			{
					ret->_state = DELETE;
				--_n;
				return true;
			}
		}
	private:
		vector<HashData<K, V>> _tables;
		size_t _n = 0; // 表中存储数据个数
	};
}

2.2链地址法(哈希桶)

开放定址法中所有的元素都放到哈希表⾥,链地址法中所有的数据不再直接存储在哈希表中,哈希表 中存储⼀个指针,没有数据映射这个位置时,这个指针为空,有多个数据映射到这个位置时,我们把 这些冲突的数据链接成⼀个链表,挂在哈希表这个位置下⾯,链地址法也叫做拉链法或者哈希桶

将 {19,30,5,36,13,20,21,12,24,96} 等这⼀组值以哈希桶的方式映射到M=11的表中

链地址法代码:
cpp 复制代码
namespace hash_bucket
{
	#include<string>
	#include<vector>
	#include<algorithm>
	using namespace std;
	template<class K, class V>
	struct HashNode
	{
		pair<K, V> _kv;
		HashNode<K, V>* _next;
		HashNode(const pair<K, V>& kv)
			:_kv(kv)
			, _next(nullptr)
		{}
	};

	template<class K>
	struct HashFunc
	{
		size_t operator()(const K& key)
		{
			return (size_t)key;
		}
	};

	template<>
	struct HashFunc<string>
	{
		size_t ret = 0;
		size_t operator()(const string& key)
		{
			for (auto e : key)
			{
				ret *= 31;
				ret += e;
			}
			return ret;
		}
	};

	template<class K, class V, class Hash = HashFunc<K>>
	class HashTable
	{
		typedef HashNode<K, V> Node;
		inline unsigned long __stl_next_prime(unsigned long n)
		{
			static const int __stl_num_primes = 28;
			static const unsigned long __stl_prime_list[__stl_num_primes] =
			{
			53, 97, 193, 389, 769,
			1543, 3079, 6151, 12289, 24593,
			49157, 98317, 196613, 393241, 786433,
			1572869, 3145739, 6291469, 12582917, 25165843,
			50331653, 100663319, 201326611, 402653189, 805306457,
			1610612741, 3221225473, 4294967291
			};
				const unsigned long* first = __stl_prime_list;
			const unsigned long* last = __stl_prime_list +
				__stl_num_primes;
			const unsigned long* pos = lower_bound(first, last, n);
			return pos == last ? *(last - 1) : *pos;
		}
	public:
		HashTable()
		{
			_tables.resize(__stl_next_prime(0), nullptr);
		}

		~HashTable()
		{
			// 依次把每个桶释放
			for (size_t i = 0; i < _tables.size(); i++)
			{
				Node* cur = _tables[i];
				while (cur)
				{
					Node* next = cur->_next;
					delete cur;
					cur = next;
				}
				_tables[i] = nullptr;
			}
		}
		bool Insert(const pair<K, V>& kv)
		{
			Hash hs;
			size_t hashi = hs(kv.first) % _tables.size();
			// 负载因⼦==1扩容
			if (_n == _tables.size())
			{
				// 这⾥如果使⽤上⾯的⽅法,扩容时创建新的结点,后⾯还要使⽤就结点,浪费了
				// 下⾯的⽅法,直接移动旧表的结点到新表,效率更好
				vector<Node*> newtables(__stl_next_prime(_tables.size() + 1), nullptr);
				for (size_t i = 0; i < _tables.size(); i++)
				{
					Node* cur = _tables[i];
					while (cur)
					{
						Node* next = cur->_next;
						// 旧表中节点,挪动新表重新映射的位置
						size_t hashi = hs(cur->_kv.first) %
							newtables.size();
						// 头插到新表
						cur->_next = newtables[hashi];
						newtables[hashi] = cur;
						cur = next;
					}
					_tables[i] = nullptr;
				}
				_tables.swap(newtables);
			}
			// 头插
			Node* newnode = new Node(kv);
			newnode->_next = _tables[hashi];
			_tables[hashi] = newnode;
			++_n;
			return true;
		}
		Node* Find(const K& key)
		{
			Hash hs;
			size_t hashi = hs(key) % _tables.size();
			Node * cur = _tables[hashi];
			while (cur)
			{
				if (cur->_kv.first == key)
				{
					return cur;
				}
				cur = cur->_next;
			}
			return nullptr;
		}
		bool Erase(const K& key)
		{
			Hash hs;
			size_t hashi = hs(key) % _tables.size();
			Node* prev = nullptr;
			Node* cur = _tables[hashi];
			while (cur)
			{
				if (cur->_kv.first == key)
				{
					if (prev == nullptr)
					{
						_tables[hashi] = cur->_next;
					}
					else
					{
						prev->_next = cur->_next;
					}
					delete cur;
					--_n;
					return true;
				}
				prev = cur;
				cur = cur->_next;
			}
			return false;
		}
	private:
		vector<Node*> _tables; // 指针数组
			size_t _n = 0; // 表中存储数据个数
	};
}

unordered_map

底层使用的是哈希表的unordered_map,一般是哈希桶实现的使用了哈希表进行 封装
实现 unordered_map的方法有多种,如红黑树法(java)
因为底层使用的是哈希表,unordered_map的增删查改效率是O(1)

unordered_map的实现

需要实现迭代器,所以底层的HashBuckte的接口也要随着更改

Myunodered_map可执行代码:

cpp 复制代码
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>  // for lower_bound

using namespace std;

// 哈希函数模板(默认支持数值类型)
template<class K>
struct HashFunc
{
    size_t operator()(const K& key) const
    {
        return (size_t)key;
    }
};

// 字符串哈希函数特化
template<>
struct HashFunc<string>
{
    size_t operator()(const string& s) const
    {
        size_t hash = 0;
        for (auto ch : s)
        {
            hash = hash * 31 + ch;
        }
        return hash;
    }
};

// 素数表(用于哈希表扩容,保证桶数为素数)
inline unsigned long __stl_next_prime(unsigned long n)
{
    static const int __stl_num_primes = 28;
    static const unsigned long __stl_prime_list[__stl_num_primes] = {
        53, 97, 193, 389, 769,
        1543, 3079, 6151, 12289, 24593,
        49157, 98317, 196613, 393241, 786433,
        1572869, 3145739, 6291469, 12582917, 25165843,
        50331653, 100663319, 201326611, 402653189, 805306457,
        1610612741, 3221225473, 4294967291
    };
    const unsigned long* first = __stl_prime_list;
    const unsigned long* last = __stl_prime_list + __stl_num_primes;
    const unsigned long* pos = lower_bound(first, last, n);
    return pos == last ? *(last - 1) : *pos;
}

// 哈希桶节点结构
template<class T>
struct HashNode
{
    T _data;
    HashNode<T>* _next;

    HashNode(const T& data)
        : _data(data)
        , _next(nullptr)
    {}
};

// 哈希表前置声明(供迭代器访问私有成员)
template<class K, class T, class KeyOfT, class Hash = HashFunc<K>>
class HashTable;

// 哈希表迭代器
template<class K, class T, class Ref, class Ptr, class KeyOfT, class Hash>
struct HTIterator
{
    typedef HashNode<T> Node;
    typedef HashTable<K, T, KeyOfT, Hash> HT;
    typedef HTIterator<K, T, Ref, Ptr, KeyOfT, Hash> Self;

    Node* _node;    // 当前指向的节点
    const HT* _ht;  // 指向哈希表(用于遍历下一个桶)

    HTIterator(Node* node, const HT* ht)
        : _node(node)
        , _ht(ht)
    {}

    // 解引用运算符
    Ref operator*() const
    {
        return _node->_data;
    }

    // 箭头运算符
    Ptr operator->() const
    {
        return &_node->_data;
    }

    // 不等比较运算符
    bool operator!=(const Self& s) const
    {
        return _node != s._node;
    }

    // 前置++运算符(遍历下一个节点)
    Self& operator++()
    {
        if (_node->_next)
        {
            // 当前桶有下一个节点,直接移动
            _node = _node->_next;
        }
        else
        {
            // 当前桶遍历完毕,找下一个非空桶
            KeyOfT kot;
            Hash hash;
            size_t hashi = hash(kot(_node->_data)) % _ht->_tables.size();
            ++hashi;

            // 遍历后续桶,直到找到非空桶或结束
            while (hashi < _ht->_tables.size())
            {
                if (_ht->_tables[hashi])
                {
                    _node = _ht->_tables[hashi];
                    break;
                }
                ++hashi;
            }

            // 所有桶遍历完毕,指向nullptr(对应end())
            if (hashi == _ht->_tables.size())
            {
                _node = nullptr;
            }
        }
        return *this;
    }
};

// 哈希桶法哈希表(核心类)
template<class K, class T, class KeyOfT, class Hash>
class HashTable
{
    // 迭代器类友元声明(允许访问私有成员_tables)
    template<class K1, class T1, class Ref1, class Ptr1, class KeyOfT1, class Hash1>
    friend struct HTIterator;

    typedef HashNode<T> Node;
public:
    // 迭代器类型定义
    typedef HTIterator<K, T, T&, T*, KeyOfT, Hash> Iterator;
    typedef HTIterator<K, T, const T&, const T*, KeyOfT, Hash> ConstIterator;

    // 构造函数(初始化桶数为最小素数)
    HashTable()
        : _tables(__stl_next_prime(0))
        , _n(0)
    {}

    // 析构函数(释放所有节点和桶)
    ~HashTable()
    {
        for (size_t i = 0; i < _tables.size(); i++)
        {
            Node* cur = _tables[i];
            while (cur)
            {
                Node* next = cur->_next;
                delete cur;
                cur = next;
            }
            _tables[i] = nullptr;  // 避免野指针
        }
    }

    // 迭代器相关接口
    Iterator Begin()
    {
        if (_n == 0)
            return End();
        // 找到第一个非空桶的第一个节点
        for (size_t i = 0; i < _tables.size(); i++)
        {
            if (_tables[i])
            {
                return Iterator(_tables[i], this);
            }
        }
        return End();
    }

    Iterator End()
    {
        return Iterator(nullptr, this);
    }

    ConstIterator Begin() const
    {
        if (_n == 0)
            return End();
        for (size_t i = 0; i < _tables.size(); i++)
        {
            if (_tables[i])
            {
                return ConstIterator(_tables[i], this);
            }
        }
        return End();
    }

    ConstIterator End() const
    {
        return ConstIterator(nullptr, this);
    }

    // 插入元素(返回迭代器和插入结果)
    pair<Iterator, bool> Insert(const T& data)
    {
        KeyOfT kot;
        // 先查找,避免重复插入
        Iterator it = Find(kot(data));
        if (it != End())
            return { it, false };

        // 负载因子 == 1 时扩容(桶数翻倍并取素数)
        if (_n == _tables.size())
        {
            vector<Node*> newTable(__stl_next_prime(_tables.size() + 1));
            // 旧桶节点重新哈希到新桶
            for (size_t i = 0; i < _tables.size(); i++)
            {
                Node* cur = _tables[i];
                while (cur)
                {
                    Node* next = cur->_next;
                    // 重新计算新桶位置
                    size_t hashi = Hash()(kot(cur->_data)) % newTable.size();
                    // 头插法插入新桶
                    cur->_next = newTable[hashi];
                    newTable[hashi] = cur;
                    cur = next;
                }
                _tables[i] = nullptr;  // 旧桶置空
            }
            _tables.swap(newTable);  // 交换新旧桶数组
        }

        // 插入新节点(头插法)
        size_t hashi = Hash()(kot(data)) % _tables.size();
        Node* newnode = new Node(data);
        newnode->_next = _tables[hashi];
        _tables[hashi] = newnode;
        ++_n;

        return { Iterator(newnode, this), true };
    }

    // 查找元素(返回迭代器)
    Iterator Find(const K& key)
    {
        KeyOfT kot;
        Hash hash;
        size_t hashi = hash(key) % _tables.size();
        Node* cur = _tables[hashi];
        // 遍历当前桶的所有节点
        while (cur)
        {
            if (kot(cur->_data) == key)
            {
                return Iterator(cur, this);
            }
            cur = cur->_next;
        }
        return End();  // 未找到
    }

    // 删除元素(返回是否成功)
    bool Erase(const K& key)
    {
        KeyOfT kot;
        Hash hash;
        size_t hashi = hash(key) % _tables.size();
        Node* prev = nullptr;
        Node* cur = _tables[hashi];

        // 遍历当前桶,查找并删除目标节点
        while (cur)
        {
            if (kot(cur->_data) == key)
            {
                // 处理头节点和中间节点的删除
                if (prev == nullptr)
                {
                    _tables[hashi] = cur->_next;
                }
                else
                {
                    prev->_next = cur->_next;
                }
                delete cur;
                --_n;
                return true;
            }
            prev = cur;
            cur = cur->_next;
        }
        return false;  // 未找到
    }

private:
    vector<Node*> _tables;  // 桶数组(存储节点指针)
    size_t _n = 0;          // 有效元素个数
};

// 基于哈希桶法的unordered_map实现
template<class K, class V, class Hash = HashFunc<K>>
class unordered_map
{
    // 提取键的仿函数(从pair<const K, V>中获取K)
    struct MapKeyOfT
    {
        const K& operator()(const pair<const K, V>& kv) const
        {
            return kv.first;
        }
    };

public:
    // 迭代器类型定义(复用哈希表的迭代器)
    typedef typename HashTable<K, pair<const K, V>, MapKeyOfT, Hash>::Iterator iterator;
    typedef typename HashTable<K, pair<const K, V>, MapKeyOfT, Hash>::ConstIterator 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();
    }

    // []运算符(插入或访问元素)
    V& operator[](const K& key)
    {
        pair<iterator, bool> ret = insert({ key, V() });
        return ret.first->second;
    }

    // 插入元素(适配pair<K, V>到pair<const K, V>)
    pair<iterator, bool> insert(const pair<K, V>& kv)
    {
        return _ht.Insert({ kv.first, kv.second });
    }

    // 查找元素
    iterator Find(const K& key)
    {
        return _ht.Find(key);
    }

    // 删除元素
    bool Erase(const K& key)
    {
        return _ht.Erase(key);
    }

private:
    HashTable<K, pair<const K, V>, MapKeyOfT, Hash> _ht;  // 哈希表对象
};

// 测试函数(验证unordered_map功能)
void test_unordered_map()
{
    unordered_map<string, string> dict;
    // 插入元素(包含重复插入)
    dict.insert({ "sort", "排序" });
    dict.insert({ "字符串", "string" });
    dict.insert({ "sort", "排序" });  // 重复插入,返回失败
    dict.insert({ "left", "左边" });
    dict.insert({ "right", "右边" });

    // 使用[]修改和插入元素
    dict["left"] = "左边,剩余";  // 修改已有元素
    dict["insert"] = "插入";      // 插入新元素
    dict["string"];               // 插入默认值(空字符串)

    // 遍历输出
    cout << "所有元素:" << endl;
    for (auto& kv : dict)
    {
        cout << kv.first << ":" << kv.second << endl;
    }
    cout << endl;

    // 查找测试
    auto it = dict.Find("insert");
    if (it != dict.end())
    {
        cout << "找到元素:" << it->first << ":" << it->second << endl;
    }
    cout << endl;

    // 删除测试
    dict.Erase("right");
    cout << "删除right后:" << endl;
    for (auto& kv : dict)
    {
        cout << kv.first << ":" << kv.second << endl;
    }
}

int main()
{
    test_unordered_map();
    return 0;
}
相关推荐
洛_尘3 小时前
数据结构--6:优先级队列(堆)
java·数据结构
让我们一起加油好吗3 小时前
【数据结构】并查集(操作详解 + 模板 + 练习)
数据结构·算法·并查集·洛谷
晨非辰4 小时前
【数据结构】排序详解:从快速排序分区逻辑,到携手冒泡排序的算法效率深度评测
运维·数据结构·c++·人工智能·后端·深度学习·排序算法
.小小陈.5 小时前
数据结构6:排序
数据结构
熬了夜的程序员13 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
立志成为大牛的小牛14 小时前
数据结构——四十一、分块查找(索引顺序查找)(王道408)
数据结构·学习·程序人生·考研·算法
前端小L16 小时前
二分查找专题(九):“降维”的魔术!将二维矩阵“拉平”为一维
数据结构·算法
她说人狗殊途16 小时前
时间复杂度(按增长速度从低到高排序)包括以下几类,用于描述算法执行时间随输入规模 n 增长的变化趋势:
数据结构·算法·排序算法
Miraitowa_cheems16 小时前
LeetCode算法日记 - Day 102: 不相交的线
数据结构·算法·leetcode·深度优先·动态规划