声明map对象时你不知道的事

在用map容器写一段程序时,发现个问题

请看下面代码

map<char, int> m;
m['a'];
cout << m['a'] << endl;

这输出什么呢?

如果用普通数据类型这么做呢?

#include<iostream>
#include<string>

using namespace std;

int main()
{
	int a;
	cout << a<<endl;//error未引用的局部变量

	bool b;
	cout << (int)b << endl;//error未引用的局部变量

	string str;
	cout << str << endl;//right

	char ch;
	cout << ch << endl;//error未引用的局部变量

	return 0;
}
大家都知道string其实是对char的封装的一个类,看了下面的代码你就懂了

#include<iostream>
#include<string>

using namespace std;

int main()
{
	string str;

	cout << str << endl;//right
	cout << str[0] << endl;//right
	cout << str[1] << endl;//error,运行前注释该行

	cout << (str[0] == 0 ? "yes" : "no") << endl;//yes
	cout << (char)0 << endl;

	return 0;
}

好,现在回到我们最初的问题

map<char, int> m;
m['a'];
cout << m['a'] << endl;
输出的是什么?

输出的是   0

这应该是自动初始化

具体实现细节,我也没找到相关资料,在这里写出只是为了告知读者有这么回事,希望读者知道的告知分享下。

下面给出其他普通数据类型的输出结果

#include <iostream>
#include<map>
#include<string>

using namespace std;

int main()
{
	//1.
	cout << "第一组--------\n";
	map<int, char> m1;
	m1[1];
	cout << m1[1] << endl;//m1[1]的Ascill码是 0
	cout << (char)0 << 1<<endl;

	//2.
	cout << "第二组--------\n";
	map<char, int> m2;
	m2['s'];
	cout << m2['s'] << endl;//输出 0

	//3.
	cout << "第三组--------\n";
	map<char, string> m3;
	m3['e'];
	cout << m3['e'] << endl;//和示例1一样的输出
	cout << m3['e'][0] << endl;//和示例1一样的输出
	//cout << m3['e'][1] << endl;//error,说明只初始化了一位
	//cout << (m3['e'][1] == '/0' ? "yes" : "no") << endl;//error

	//4.
	cout << "第四组--------\n";
	map<char, bool> m4;
	m4['t'];
	cout << m4['t'] << endl;//输出 0
	

	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值