深圳幻海软件技术有限公司 欢迎您!

c++ unordered_map和map的区别

2023-06-07

一、unordered_map介绍unordered中文翻译即“无序的”,自然地,unordered_map也就是不排序的map的意思。unordered_set与set和unordered_map与map是可以类比的,它们的区别大致是一样的。unordered_map在c++11加入的标准模板库,

一、unordered_map介绍

unordered中文翻译即 “无序的” ,自然地,unordered_map也就是不排序的map的意思。unordered_set与set和unordered_map与map是可以类比的,它们的区别大致是一样的。

unordered_map在c++11加入的标准模板库,c++11以前是无法使用unordered_map、unordered_set、auto、stoi等标准模板的。unordered_map包含在unordered_map头文件中,即如果想要使用时,引入下面代码即可

#include<unordered_map>
using namespace std;//注意需要使用命名空间
  • 1
  • 2

二、unordered_map和map的区别

1、实现不同

  • unordered_map底层是用哈希表实现的
  • map底层是用红黑树实现的

2、性能不同

  • unordered_map是不按键值排序的,插入的时间是O(logn),查询时间是O(1)
  • map是按键值排序的,插入的时间是O(logn),查询时间是O(logn)

3、使用范围不同

  • unordered_map的使用比较局限,它的key只能是int、double等基本类型以及string,而不能是自己定义的结构体
  • map可以支持所有类型的键值对

三、使用建议

不需要按键值排序就用unordered_map,实在需要的话就要map
unordered_set和set也是一样的

四、使用方法

unordered_map和map的使用几乎是一致的,只是头文件和定义不同

下面给出定义的示例代码:

#include<iostream>
#include<map>//使用map需要的头文件 
#include<unordered_map>//使用unordered_map需要的头文件 
#include<set>//使用set需要的头文件 
#include<unordered_set>//使用unordered_set需要的头文件 
using namespace std;
int main(){
map<int,int> m1;
unordered_map<int,int> m2;

set<int> s1;
unordered_set<int> s2;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

如果想要学习map的使用方法,可看我的另一篇文章
c++ map用法 入门必看 超详细

如果想要学习set的使用方法,可看我的另一篇文章
c++ set用法 入门必看 超详细

dev c++默认是不使用c++11的,如果想要使用,可看我的另一篇文章
dev使用c++11教程

最后,加油!兄弟萌!!

文章知识点与官方知识档案匹配,可进一步学习相关知识
算法技能树首页概览47725 人正在系统学习中