unordered_set与unordered_map

本文介绍了unordered_set和unordered_map在C++中的使用,包括它们如何通过哈希函数存储和查找字符与整数,以及如何进行初始化、插入、查找和遍历操作。重点讲解了这两个容器的特点,如无重复元素和高效的查找性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

unordered_set

将字符通过哈希函数转成数组的下标,然后将字符存放在下标处,这样我们可快速查找到字符,
set容器不可以有重复的元素

1、初始化

unordered_set<char>set;//构造一个空的容器
unordered_set<char>set(str.begin(),string.end());//将一个字符串str初始化set容器

2、插入、查找、遍历

unordered_set<int> set;
for(int i = 0; i < list.size(); i++){
 set.insert(list[i]);
 for(unordered_set<int> :: iterator i = set.begin(); i != set.end(); i++)
 {
  cout << *i << endl;
 }
 cout << "find 39" << *set.find(39) << endl;
 cout << "count 14" << set.count(5) << endl;//找到就返回1
}
for(unordered_set<int> :: iterator i = set.begin(); i != set.end(); i++)//创建出一个迭代器
{
     cout << *i <<endl;
}

unordered_map

将字符串通过哈希函数转成数组的下标,然后我们可以在这个地方存放数据(出现次数之类的,也可以放别的)

1、构造函数

unordered_map<int,int>map;//构造空的容器
unordered_map<string,int>map{{"jan",44},{"jim",33},{"joe",99}};//直接构造
unordered_map<string,int>map(hashmap,begin(),hashmap.end());//范围初始化

2、插入、查找、遍历

map.insert(pair<string,int>)(word,1);//map容器中直接添加数据

unordered_map<int,int> map;
for(int i = 0; i < list.size(); i++)  
      map[i] = list[i]//将数据写入map中
cout << map[0] << endl;
for(unordered_map<int,int>::iterator i = map.begin(); i != map.end(); i++)//创建出一个迭代器
   cout << i ->first << ' ' << i ->second << endl;
if(map.find(3) != map.end())//map.find(3)会返回一个迭代器
         cout <<"find key = " << map.find(3)->first << " value =" << map.find(3)->second <<endl;
if(map.count(5) > 0)
  cout << "find 5: " << map.count(5) <<endl;//要是找到就返回1,不然就返回0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值