C++ map的方法

map的使用方法

1.定义map
	map<int , string> mp;
2.数据插入(其中的两种方式)
	pair<int , string> value(1 , "one");
	mp.insert(value);
	mp.insert( pair<int , string>(1 , "one") );
3.循环输出
	 map<int, string> mapStudent;  
	 mapStudent[1] =  "student_one";  
	 mapStudent[2] =  "student_two";  
	 mapStudent[3] =  "student_three";  
	 map<int, string>::iterator  iter;  
	 for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  {  
	    cout<<iter->first<<"   "<<iter->second<<endl;  
	 }  
4.find() 方法
	mp[3] =  "student_three";
	map<int , string>::iterator it=mp.find(3);
	if(it!=mp.end()){
		cout<<it->second<<endl;
	}
5.count() 方法

出现元素3的次数,这个输出1

	cout<<mp.count(3)<<endl; 
6.swap() 方法

交换两个map的值

	map<int, string> mp;  
	mp[1] =  "student_one";  
	mp[2] =  "student_two";  
	mp[3] =  "student_three";  
	
	map<int, string> mp1; 
	mp1[1]="qqqqq";
	mp1[2]="wwwww";

	swap(mp,mp1);
	
	map<int, string>::iterator  iter;  
	for(iter = mp.begin(); iter != mp.end(); iter++)  {  
		cout<<iter->first<<"   "<<iter->second<<endl;  
	}  
其他基本函数的使用
  • mp.begin() 返回指向map头部的迭代器
  • mp.clear() 删除所有元素
  • mp.empty() 如果map为空则返回true
  • mp.end() 返回指定map末尾的迭代器
  • mp.erase(2) 删除元素2
  • mp.size() 返回map中元素的个数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值