1.建立基本数据类型的哈希表

unordered_map<int,int> m; //<string,string>,<char,char>

2.向哈希表中添加元素

1).insert 函数

m.insert(pair<int,int>(1, 10));
m.insert(pair<int,int>(2, 20));

2).用数组方法直接添加

m[3]=30;
m[4]=40;

3.成员函数

begin(),end()函数

m.begin() //指向哈希表的第一个容器
m.end()  //指向哈希表的最后一个容器,实则超出了哈希表的范围,为空

find()查找函数

m.find(2)  //查找key为2的键值对是否存在 ,若没找到则返回m.end()
if(m.find(2)!=m.end()) //判断找到了key为2的键值对

count() 查找函数

查找哈希表中key为3的键值对,返回其数量,为1,则找到,若没找到则返回0

m.count(3)  //返回 1
m.count(5)   //返回0

size()函数

m.size()   //返回哈希表的大小

empty()函数

m.empty()  //判断哈希表是否为空,返回值为true/false

clear()函数

m.clear()  //清空哈希表

swap()函数

交换两个哈希表中的元素,整个哈希表的键值对全部都交换过去

unordered_map<int,int> m1;
unordered_map<int,int> m2;
m1.swap(m2);
swap(m1,m2);

哈希表的遍历

第一种遍历

unordered_map<int, int> count;
for (auto p : count) {
	int front = p.first;   //key
    int end = p.second;   //value
}

第二种遍历

unordered_map<int, int> count;
for(auto it=m.begin();it!=m.end();it++)
{
    int front = it->first;   //key
    int end = it->second;   //value
}
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐