服务器之家

服务器之家 > 正文

c++ map索引不存在的key可能导致的后果分析

时间:2021-10-14 13:40     来源/作者:鱼竿钓鱼干

今天调这个调了很久才发现这个问题,所以记录以下
测试代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    map<int,int>mp_int;
    map<string,string>mp_string;
    map<char,char>mp_char;
    mp_int[1]=10;
    string a="abc",b="xzy",c="def";
    mp_string[a]=b;
    mp_char['a']='b';
    cout<<"正常索引"<<endl;
    for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl;
    
    cout<<"访问不存在的键"<<endl;
    cout<<mp_int[2]<<endl<<mp_string[c]<<endl<<mp_char['c']<<endl;
    
    cout<<"变化"<<endl;
    for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl;
    
    return 0;
}

OUT PUT

正常索引
1 10
abc xzy
a b
访问不存在的键
0
变化
1 10
2 0
abc xzy
def
a b
c

可以发现不存在的key在被索引后被添加到了map中并被赋予了一个默认值(一般的,整数为0,字符,字符串为空)

需要注意的是,只要发生了索引,就会导致如上错误,即使他们在if语句里

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<bits/stdc++.h>
using namespace std;
 
int main()
{
    map<int,int>mp_int;
    map<string,string>mp_string;
    map<char,char>mp_char;
    mp_int[1]=10;
    string a="abc",b="xzy",c="def";
    mp_string[a]=b;
    mp_char['a']='b';
    cout<<"正常索引"<<endl;
    for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl;
    
    cout<<"访问不存在的键"<<endl;
    if(mp_int[2]);
    if(mp_string[c]==a);
    if(mp_char['c']);
    
    cout<<"变化"<<endl;
    for(auto &i:mp_int)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_string)cout<<i.first<<" "<<i.second<<endl;
    for(auto &i:mp_char)cout<<i.first<<" "<<i.second<<endl;
    
    return 0;
}

上面的代码会产生同样的结果

当你想要再次使用(循环)这些键的时候就会出错,你会使用到实际并不存在的key

避免方法是在索引前使用find或者count来判断键是否存在

到此这篇关于c++ map索引不存在的key可能导致的后果分析的文章就介绍到这了,更多相关c++ map索引内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_39354847/article/details/111087774

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部