C语言学习过程记录15 映射容器map

1.map的基本操作

//map是一种关联式的容器,提供一对一的映射关系,包括关键字+值。第一个(first)被称为关键字(key),第二个(second)被称为值(value)。每个key只能出现一次,而同一个key可以对应不同的值


#include<map>//头文件
#include<iterator>
using namespace std; 
int main()
{

	map<string,string> friends;//创建map对象 关键字key为string,值value为string。
	map<int,string> mp;//创建map对象 关键字key为int类型,值value为string。 
	friends["Jack"]="123456";//在friends中插入元素 
	friends["Rose"]="432432";
	friends["Sam"]="664332";
	mp[1]="Jack";//在mp中插入元素
	mp[2]="Rose";
	mp[3]="Sam";
	map<int,string>::iterator it;//迭代器 
	for(it = mp.begin();it != mp.end();it++)
	cout<<it->first<<"->"<<it->second<<endl;
	cout<<mp.count(1)<<endl;//返回容器中元素个数
	mp.erase(1);//删除mp中的某个元素 
	 for(it = mp.begin();it != mp.end();it++)
	cout<<it->first<<"->"<<it->second<<endl;
	cout<<mp.size()<<endl;//返回mp中元素个数
	mp.clear();//清空mp中所有元素 
	cout<<mp.empty()<<endl; //判断mp是否为空,是则返回1,不是则返回0 
	mp[1]="Jack";
	cout<<mp.empty()<<endl;//
	 
	 return 0;
}

2.map实操之火车到站问题

输入火车的所有站点数目M,输入火车的经停站数目N,输入火车的所有站点名字,输入火车的所有经停站的名字,判断每个站火车是否经停

输入样例:                                                                       

5 3                                                
兰州 西安 郑州 上海 杭州                            
广州 上海 西安    
输出样例:                                  
NO
Yes
NO
Yes
NO

代码如下:

#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
	map<int,string> allstation;
	map<int,string> stopstation;
	string name;
	int N = 0;
	int M = 0;
	int i = 0;
	cin>>N;
	cin>>M;
	for(i=0;i<N;i++)
	{
		cin>>name;
		allstation[i]=name;
	}
	
	for(i=0;i<M;i++)
	{
		cin>>name;
		stopstation[i]=name;
	}
	map<int,string>::iterator it1;
	map<int,string>::iterator it2;
	for(it1 = allstation.begin();it1!= allstation.end();it1++)
	{
		for(it2 = stopstation.begin();it2 != stopstation.end();)
		{
		
			if(it1->second == it2->second)
			{
				cout<<"Yes"<<endl;
				break;
			}
			else
			{
				it2 ++;
			}
			if(it2 == stopstation.end())
			cout<<"NO"<<endl;
		}
	}
	
	return 0;
}

运行结果:

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值