在用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; }