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 << "
";
	}
	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;

}

  • 运行结果:

原文地址:https://www.cnblogs.com/musecho/p/11996287.html