map

蓝桥杯 map-LMLPHP
蓝桥杯 map-LMLPHP

代码示例

#include<iostream>
#include<map>
using namespace std;
int main(){
	//创建并初始化map
	map<int,string> myMap={{1,"Apple"},{2,"Banana"},{3,"Orange"}} ;
	//插入元素
	myMap.insert(make_pair(4,"Grapes")) ;
	//查找和访问元素
	cout<<"Value at key 2:"<<myMap[2]<<endl;
	//遍历打印map中的元素
	for(const auto& pair:myMap){
		cout<<"key:"<<pair.first<<",value:"<<pair.second<<endl;
	} 
	//删除元素
	myMap.erase(3);
	//判断元素是否存在
	if(myMap.count(3)==0) {
		cout<<"key 3 not found"<<endl;
	}
	//清空map
	myMap.clear();
	//判断map是否为空
	if(myMap.empty()){
		cout<<"map is empty"<<endl; 
	} 
	return 0;
}

蓝桥杯 map-LMLPHP
蓝桥杯 map-LMLPHP

11-17 08:12