聲明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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章