unordered_map和unordered_set的介绍和使用
一.应用场景
unordered_map和unoredered_set的用法存在高度相似,只是作用发生了一些变化,我们来进行介绍!
当我们面对数量庞大且对数据进行无序性的处理时,我们就可以利用unoredered_map和unordered_set进行相关处理。
二.pair的介绍和使用
直接进行构造:

在c++11中我们也可以:


#include<iostream>
using namespace std;
int main()
{
//直接构造法
pair<int, string> a(1, "alice");
cout << a.first << endl;
cout << a.second << endl;
//利用花括号
pair<int, string> b = { 2,"faxe" };
cout << b.first << endl;
cout << b.second << endl;
return 0;
}
我们对pair指针进行访问的时候,可以用first和second来进行,并且pair可以进行比较先比较first在进行比较second,主要用于二维空间来进行。
三.容器的比较
unordered和set:
(1).unordered要求Key转化成整形且支持等于比较,set的Key则支持的是小于比较
(2).set的是双向迭代器,unordered_set的是单项迭代器。
(3).set的底层是红黑树而ordered_set的底层是哈希表
(4).比较效率的话,ordered_set更快一些是O(1),而set的效率是O(logN)
四.容器的基本操作



int test()
{
const size_t N = 100000;
unordered_set<int> us;
set<int> s;
vector<int> v;
//对数组进行预留空间
v.reserve(N);
//生成测试数据
srand(time(0));
for (size_t i = 0; i < N; i++) {
v.push_back(rand() + i);
}
//插入操作
int begin1 = clock();
for (auto e : v) {
s.insert(e);
}
int end1 = clock();
cout << "set 插入耗时:" << end1 - begin1 << endl;
int begin2 = clock();
//进行预留空间
us.reserve(N);
for (auto e : v) {
us.insert(e);
}
int end2 = clock();
cout << "unordered_set 插入耗时:" << end2 - begin2 << endl;
//查找操作的耗时
int m1 = 0;
int begin3 = clock();
for (auto e : v) {
auto ret = s.find(e);
if (ret != s.end()) {
m1++;
}
}
int end3 = clock();
cout << "set 耗时:" << end3 - begin3 << endl;
int m2 = 0;
int begin4 = clock();
for (auto e : v) {
auto ret = us.find(e);
if (ret != us.end()) {
m2++;
}
}
int end4 = clock();
cout << "unordered_set 耗时:" << end4 - begin4 << endl;
//删除操作的比较
int begin5 = clock();
for (auto e : v) {
s.erase(e);
}
int end5 = clock();
cout << "set 耗时:" << end5 - begin5 << endl;
int begin6 = clock();
for (auto e : v) {
us.erase(e);
}
int end6 = clock();
cout << "unordered_set 耗时:" << end6 - begin6 << endl;
cout << "set的最终元素个数:" << s.size() << endl;
cout << "unordered_ser的最终元素个数:" << us.size() << endl;
return 0;
}
int main()
{
test();
return 0;
}
五.总结
虽然我们的unordered_set1和unordered_map的效率更快一些,但是我们不能忽略数据是否需要有序性的问题,如果对数据的有序性有要求,则只能用set和map。
更多推荐

所有评论(0)