C++ STL map的构造与属性

#include<iostream>
#include<map>
#include<algorithm>
#include<cstring>
using namespace std;

//对应好参数类型 
void fun(pair<int,char> pr)
{
	//键值  first            实值  second 
	cout << pr.first << " " <<pr.second << endl;
	//输出是以键值排好序输出的 
}

void MapConstruct()
{
	//无参 
	//pair<int,char>  实际上是一个结构体 
	typedef pair<int,char> in_pair;
	pair<map<int,char>::iterator,bool> pr;  
	//无参 				//键值不可以重复 
	map<int,char> mp;   // < \ >  两个类型  一个键型 一个实型
	//排序时用  键值  排序
	mp.insert(pair<int,char>(1,'a'));
	pr=mp.insert(in_pair(2,'a'));   
	//查看insert的返回值  bool返回插入是否正确  (即键值是否重复) 
	//cout << pr << endl;
	mp.insert(in_pair(5,'a'));
	mp.insert(in_pair(4,'a'));
	
	map<int,char> :: iterator ite =mp.begin();		//迭代器
	/*****************************************/ 
	/*迭代器只可以自加  不可以直接加某个数值 */ 
	ite++; ite++;ite++;ite++;
	mp.insert(ite,in_pair(3,'a'));
	//随机位置插入键值,键值会排序
	
	map<int,char> mp1;
	mp1.insert(in_pair(7,'a'));
	//将mp整段插入到mp1当中 
	mp1.insert(mp.begin(),mp.end());
	 
	
	//一个参数
	map<int,char> mp2(mp1); 
	for_each(mp2.begin(),mp2.end(),fun);
}

void MapOther()
{
	typedef pair<int,char> in_pair;
	//pair 跟map的元素要一样 
	map<int,char> mp;
	char c;
	for(int i=1;i<=5;i++)
	{
		scanf("%c",&c);
		getchar();
		mp.insert(in_pair(i,c));
	}
	cout << endl;
	cout << mp.size() << endl;
	
	//查找键值…   有值返回 1  否则返回0 
	cout << mp.count(1) << endl;
	//查看是否为空 
	cout << mp.empty() << endl; 
	
	//头尾迭代器 begin  end
	 
	//for_each(mp.begin(),mp.end(),fun);
	
	//用迭代器进行输出
	map<int,char> :: iterator ite = mp.begin();
	for(ite;ite!=mp.end();ite++)
	{
		cout << ite->first << " " << ite->second << endl; 
	}
}

int main()
{
	//MapConstruct();
	MapOther();
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值