C++ STL unordered_map获取元素的4种方法(超级详细)

1年前 (2024-04-27)
通过前面的学习我们知道,unordered_map 容器以键值对的方式存储数据。为了方便用户快速地从该类型容器提取出目标元素(也就是某个键值对的值),unordered_map 容器类模板中提供了以下几种方法。

1) unordered_map 容器类模板中,实现了对 [ ] 运算符的重载,使得我们可以像“利用下标访问普通数组中元素”那样,通过目标键值对的键获取到该键对应的值。

举个例子:

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"Python教程","http://c.biancheng网站站点" rel="nofollow" />

http://c.biancheng网站站点" rel="nofollow" />

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建空 umap 容器

unordered_map<string, string> umap;

//[] 运算符在 = 右侧

string str = umap["STL教程"];

//[] 运算符在 = 左侧

umap["C教程"] = "http://c.biancheng网站站点" rel="nofollow" /> C教程 http://c.biancheng网站站点" rel="nofollow" />

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"Python教程","http://c.biancheng网站站点" rel="nofollow" />

http://c.biancheng网站站点" rel="nofollow" />

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"Python教程","http://c.biancheng网站站点" rel="nofollow" /> Python教程 http://c.biancheng网站站点" rel="nofollow" />

#include <iostream>

#include <string>

#include <unordered_map>

using namespace std;

int main()

{

//创建 umap 容器

unordered_map<string, string> umap{

{"Python教程","http://c.biancheng网站站点" rel="nofollow" />

http://c.biancheng网站站点" rel="nofollow" />