C++:map用法及元素的默認值


C++:map用法

一、map基本用法


鍵值對

第一個參數為鍵的類型,第二個參數為值的類型。


  • 源代碼
#include <iostream>
#include <string>
#include <map>

using namespace std;

int main() {
	map<int,string> ::iterator iter;  //迭代器iterator:變量iter的數據類型是由map<int,string>定義的iterator類型
	map<int,string> myMap;

//添加數據
	myMap[1] = "one";
	myMap[2] = "two";
	myMap[3] = "three";

//遍歷map
	iter = myMap.begin();             //指向map首對元素
	cout<<"myMap:"<<endl;
	for (iter; iter != myMap.end(); iter++) {  //myMap.end()指向map最后一對元素的后一對元素
		cout << (*iter).first << " " << (*iter).second << "\n";
	}
	cout<<endl;

//構造map
	map<int, string> myMap2(myMap.begin(), myMap.end());//用myMap指定范圍內的元素對,構造myMap2
	map<int, string> myMap3(myMap);//用myMap構造myMap2

	iter=myMap2.begin();
	iter++;
	cout<<"myMap2: "<<(*iter).first<<" " << (*iter).second<<endl<<endl;

	iter=myMap3.begin();
	iter++;
	iter++;
	cout<<"myMap3: "<<(*iter).first<<" " << (*iter).second<<endl;

	return 0;
}


  • 運行結果:



二、map元素的默認值


當map內元素值為int類型或常量時,默認值為0。

當為String類型時,默認值不明,不顯示


  1. map內元素值為int類型
#include <iostream>
#include <map>
using namespace std;

int main(){
	map<int,int> table;

	table[1]=1;

	cout<<table[0]<<endl;
	cout<<table[1]<<endl;
	return 0;

}


  • 運行結果:



  1. map內元素值為常量類型
#include <iostream>
#include <map>
using namespace std;

enum Symbols { //第一個枚舉元素默認值為0,后續元素遞增+1。
	// 終結符號 Terminal symbols:TS
	TS_I,           // i
	TS_PLUS,        // +
	TS_MULTIPLY,	// *
	TS_L_PARENS,    // (
	TS_R_PARENS,    // )
	TS_EOS,         // #
	TS_INVALID,     // 非法字符

	// 非終結符號 Non-terminal symbols:NS
	NS_E,           // E
	NS_T,           // T
	NS_F            // F
};

int main(){
	map<int,enum Symbols> table;

	table[1]=TS_PLUS;

	cout<<table[0]<<endl;
	cout<<table[1]<<endl;

	return 0;

}


  • 運行結果:


  1. map內元素值為string類型
#include <iostream>
#include <map>
#include <string>

using namespace std;

int main(){
	map<int,string> table;

	table[1]="abc";

	cout<<table[0]<<endl;
	cout<<table[1]<<endl;
	return 0;

}

  • 運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM