无序关联容器的使用

unordered_set

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <unordered_map> //map映射表 存储的key-value
#include <unordered_set> //set集合,只存储key
#include <string>
using namespace std;

int main()
{
//set的使用
unordered_set<int> set1;
//增加
set1.insert(1010);
set1.insert(1020);
set1.insert(1030);
//查询
auto it=set1.find(1010);
if(it==set1.end())
cout<<"no find 1010"<<endl;
else
cout<<*it<<endl;
//删除
set1.erase(1010);
it=set1.find(1010);
if(it==set1.end())
cout<<"no find 1010"<<endl;
else
cout<<*it<<endl;
//遍历
for(it=set1.begin();it!=set1.end();++it)
cout<<*it<<" ";
cout<<endl;
for(auto &key:set1)
cout<<key<<" ";
cout<<endl;
return 0;
}

unordered_map

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <unordered_map> //map映射表 存储的key-value
#include <unordered_set> //set集合,只存储key
#include <string>
using namespace std;

int main()
{
//map的使用
unordered_map<int,string>map1;
//增加
map1.insert({10,"zhangwei"});
map1.insert({20,"dali"});
map1[30]="tanyishan";
//查询,it这里是迭代器类型,指向的是map里面的元素,Pair对象。
auto it=map1.find(10);
if(it==map1.end())
cout<<"10 not exist"<<endl;
else
cout<<"key:"<<it->first<<" value:"<<it->second<<endl;
//删除
map1.erase(10);
it=map1.find(10);
if(it==map1.end())
cout<<"10 not exist"<<endl;
else
cout<<"key:"<<it->first<<" value:"<<it->second<<endl;
//遍历
for(it=map1.begin();it!=map1.end();++it)
cout<<it->first<<" "<<it->second<<endl;
for(auto it : map1)
cout<<it.first<<" "<<it.second<<endl;
return 0;
}