本文翻译自: C++ Unordered Map
C++的STL中的unordered_map是一种无序关联容器,提供了一种无序map或字典数据结构的功能。
与常规的map相反,在一个unordered map中键的顺序是无定的。
同时unordered map是通过散列表实现的,而常规的map是通过二叉搜索树实现的。
1.创建C++的unordered_map
使用头文件:
#include <unordered_map>
一旦我们引入了这个头文件,通过下面的句法规范,我们能够创建一个unordered map:
unordered_map<key_type, value_type> ump;
比如说:
// create an unordered_map with integer key and value
unordered_map<int, int> ump_integer;
// create an unordered_map with string key and int value
unordered_map<string, int> ump_string;
2.初始化一个unordered map:
// Initializer List
unordered_map<string, int> unordered_map1 = {
{"One", 1},
{"Two", 2},
{"Three", 3}
};
// Uniform Initialization
unordered_map<string, int> unordered_map2 {
{"One", 1},
{"Two", 2},
{"Three", 3}
};
这两种方法都可
3.案例1: C++ unordered_map
代码如下:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
// uniform initialization
unordered_map<string, int> unordered_map1 {
{"One", 1},
{"Two", 2},
{"Three", 3}
};
cout << "Key - Value" << endl;
// loop across the unordered map
// display the key-value pairs
for(const auto& key_value: unordered_map1) {
string key = key_value.first;
int value = key_value.second;
cout << key << " - " << value << endl;
}
return 0;
}
输出:
Key - Value
Three - 3
Two - 2
One - 1
在上述案例中,每一个元素(键值对)被存储在变量key_value中,其中:
key_value.first —— 存储键
key_value.second —— 存储值
从结果看出,输出是无序的。这是因为这些元素并没有按照特定的顺序存储。
注: 在C++ 17中,你可以使用 structure bindings来简化上面代码中的for循环:
for(const auto& [key, value]: unordered_map1) {
cout << key << " - " << value << endl;
}
4.将一个unordered map中的内容复制到另一个新的unordered map中
可以采用类似于下面的方法:
unordered_map<string, int> unordered_map_1 {
{"One", 1},
{"Two", 2},
{"Three", 3}
};
unordered_map<string, int> unordered_map_2(unordered_map_1.begin(), unordered_map_1.end());
5.unordered map的方法:
6.向一个unordered map中插入键值对
可以使用insert( )函数或[ ]操作符:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> unordered_map1;
// insert key-value pair {"One", 1}
unordered_map1["One"] = 1;
// insert a pair {"Two", 2}
unordered_map1.insert({"Two", 2});
// insert two pairs {"Three", 3}, {"Four", 4}
unordered_map1.insert({{"Three", 3}, {"Four", 4}});
cout << "Key - Value" << endl;
// display elements of unordered_map1
for(const auto& key_value: unordered_map1) {
string key = key_value.first;
int value = key_value.second;
cout << key << " - " << value << endl;
}
return 0;
}
输出结果:
Key - Value
Four - 4
Two - 2
Three - 3
One - 1
7.访问unordered map中的值
可以使用如下两种办法:
(1) at( ) —— 返回特定键所对应的值。
(2) [ ] —— 返回特定键所对应的值
例如:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, string> capital_city {
{"Nepal", "Kathmandu"},
{"India", "New Delhi"},
{"Australia", "Canberra"}
};
cout << "Capital of Nepal is " << capital_city["Nepal"] << endl;
cout << "Capital of Australia is " << capital_city.at("Australia");
return 0;
}
输出:
Capital of Nepal is Kathmandu
Capital of Australia is Canberra
建议使用at( )而不是[ ],如果传入的键不存在,at( )就会抛出异常,而[ ]会给这个键配一个脏数据。
8.改变unordered map中的值
可以使用at( )方法或[ ]操作符去改变unordered map中的值,例如:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, string> capital_city {
{"India", "Calcutta"},
{"Pakistan", "Karachi"},
};
cout << "Old Capitals:" << endl;
cout << "India : " << capital_city["India"] << endl;
cout << "Pakistan : " << capital_city["Pakistan"];
// change value for "India" using []
capital_city["India"] = "New Delhi";
// change value for "Pakistan" using at()
capital_city.at("Pakistan") = "Islamabad";
cout << "\n\nNew Capitals:" << endl;
cout << "India : " << capital_city["India"] << endl;
cout << "Pakistan : " << capital_city["Pakistan"];
return 0;
}
输出:
Old Capitals:
India : Calcutta
Pakistan : Karachi
New Capitals:
India : New Delhi
Pakistan : Islamabad
9.移除unordered map中的元素
我们可以用erase( )方法来移除unordered map中的特定键的元素,例如:
#include <iostream>
#include <unordered_map>
using namespace std;
// function prototype for display_unordered_map()
void display_unordered_map(const unordered_map<int, string> &);
int main() {
unordered_map<int, string> student {
{111, "John"},
{132, "Mark"},
{143, "Chris"}
};
cout << "Initial Unordered Map:\n";
display_unordered_map(student);
// remove element with key: 143
student.erase(143);
cout << "\nFinal Unordered Map: \n";
display_unordered_map(student);
return 0;
}
// utility function to print unordered_map elements
void display_unordered_map(const unordered_map<int, string> &umap){
for(const auto& key_value: umap) {
int key = key_value.first;
string value = key_value.second;
cout << key << " - " << value << endl;
}
}
输出:
Initial Unordered Map:
143 - Chris
132 - Mark
111 - John
Final Unordered Map:
132 - Mark
111 - John
如果想要擦除所有的数据,就用clear( )。
10.检查某个键在unordered map中是否存在
可以使用以下这两种方法:
(1) find( ) —— 如果键存在,返回元素迭代器,否则返回end( )迭代器。
(2) count( ) —— 如果这个键存在就返回1,否则就返回0
比如:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<int, string> student{
{111, "John"},
{132, "Mark"},
{143, "Chris"}
};
cout << "Using find():" << endl;
cout << "Does id " << 143 << " exist? ";
// find() returns student.end() if the key is not found
if (student.find(143) != student.end()) {
cout << "Yes";
}
else {
cout << "No";
}
cout << "\n\nUsing count():" << endl;
cout << "Does id " << 1433 << " exist? ";
// count() returns 0 if the key doesn't exist
if (student.count(1433)) {
cout << "Yes";
}
else {
cout << "No";
}
return 0;
}
输出:
Using find():
Does id 143 exist? Yes
Using count():
Does id 1433 exist? No