C++中unordered_map几种按键查询比较

unorder_map有3种常见按键查值方法。

使用头文件,以及命名空间std。

第一种是按键访问。如果键存在,则返回键对应的值;如果键不存在,则返回0;

1 #include<unordered_map>
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     unordered_map<int, int> test_map;
 8     cout << test_map[0] << endl;  // 键0不存在,输出0
 9     test_map[0] = 1;  // 加入键0
10     cout << test_map[0] << endl;  // 键0存在,输出键对应的值
11     return 0;
12 }
13 
14 /*
15 0
16 1
17 */

利用第一种访问方式,可以简单地往哈希表里面添加元素。

1     test_map[1]++;
 2     test_map[2] = test_map[2] + 1;
 3     cout << test_map[0] << endl << test_map[1];
 4 
 5     /*
 6     1
 7     1
 8     可以发现上面两种方式都可以往哈希表中添加元素和改变元素的值,用起来比较方便。
 9     在进行比较的时候,不需要判断哈希表中键是否存在。
10     */

第二种是使用哈希表成员函数count查询,count函数计算哈希表中要查询键的个数,在哈希表中返回的值只有0和1

即哈希表中是否存在要查询的键。

1 #include<unordered_map>
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     unordered_map<int, int> test_map;
 8 
 9     test_map[0] = 1;
10     test_map[1] = 2;
11     cout << test_map.count(0) << endl << test_map.count(1) << endl << test_map.count(2) << endl;
12    //  哈希表中存在键0和1,因此输出为1 1 0
13     return 0;
14 }
15 
16 /*
17 1
18 1
19 0
20 */

第三种方式是使用哈希表成员函数find进行查询,如果返回的值是哈希表的迭代器类型。

如果等于哈希表的末尾,则表示键不在哈希表中。

如果不等于哈希表的末尾,则可以通过iter->first来访问要查询的键,通过iter->second来访问要查询的键对应的值。

1 #include<unordered_map>
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     unordered_map<int, int> test_map;
 8 
 9     test_map[0] = 1;
10     int key = 0;
11     unordered_map<int, int>::iterator tmp = test_map.find(key);
12     if (tmp == test_map.end()) {
13         cout << "no key " << key << endl;
14     }
15     else {
16         cout << "exist key " << key << endl;
17         cout << "first: " << tmp->first << " second: " << tmp->second << endl;
18     }
19     cout << endl;
20     key = 1;
21     tmp = test_map.find(key);
22     if (tmp == test_map.end()) {
23         cout << "no key " << key << endl;
24     }
25     else {
26         cout << "exist key " << key << endl;
27         cout << "first: " << tmp->first << " second: " << tmp->second << endl;
28     }
29     return 0;
30 }
31 
32 /*
33 exist key 0
34 first: 0 second: 1
35 
36 no key 1
37 */

以上就是unordered_map的几种按键查询比较。

最近在LeetCode上做题的时候,对unordered_map的查询以及返回值有一些疑惑,所以写了这篇博客。

如果对上面有问题或者上面有错误,欢迎大家在评论区留言
原文链接: https://www.cnblogs.com/proton/p/13415663.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/200978

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:38
下一篇 2023年2月12日 下午8:38

相关推荐