温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c++ 中map索引不存在如何解决

发布时间:2020-12-15 15:25:55 来源:亿速云 阅读:822 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关c++ 中map索引不存在如何解决,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

测试代码

#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语句里

#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索引不存在如何解决有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI