STL第七部分unordered_map
✨1、unordered_map【哈希表】
unordered_map是C++中的哈希表,可以在任意类型与类型之间做映射
① 头文件
#include <unordered_map>
② 初始化
// unordered_map<类型, 类型> 变量名;
unordered_map<int,int> um1;
③ 常用函数
1. 变量名["键名"]=值 插入
// 初始化及插入
unordered_map<string,string> um1;
um1["c++"] = "good";
2. 变量名["键名"] 查询
// 查询
std::cout << "um1[\"c++\"]:" << um1["c++"] << endl; // um1["c++"]:good
3. count() 和 find() 判断某个值是否存在
// 判断某个值是否存在,但是依据键名查询值是否存在
std::cout << "um1.count():" << um1.count("c++") << endl; // 1
int s = um1.find("c++") != um1.end();
std::cout << "um1.find():" << s << endl; // 1
④ 遍历
// 遍历
std::cout << "遍历um1:\n";
for (auto &tmp: um1){
std::cout << tmp.first << "\t" << tmp.second << endl;
}
①至④运行截图
附全文代码
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
// 初始化及插入
unordered_map<string,string> um1;
um1["c++"] = "good";
um1["f"] = "study";
// 查询
std::cout << "um1[\"c++\"]:" << um1["c++"] << endl;
// 判断某个值是否存在,但是依据键名查询值是否存在
std::cout << "um1.count():" << um1.count("c++") << endl;
int s = um1.find("c++") != um1.end();
std::cout << "um1.find():" << s << endl;
// 遍历
std::cout << "遍历um1:\n";
for (auto &tmp: um1){
std::cout << tmp.first << "\t" << tmp.second << endl;
}
return 0;
}