基础数据结构(3)映射

从零起步看算法(第十八天 5.4)

//映射

1.映射基本操作

 

//引用

#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
	
	map<string,int> dict; 
	
	//构造一个映射
	
	dict.insert(pair<string,int>("Tom",1));
	
	//映射的插入
    //元祖的结构 
	dict.insert(pair<string,int>("Jony",2));
	dict.insert(pair<string,int>("Mary",3));
	dict.insert(pair<string,int>("Tom",2));//不会改变原有映射
	
	
	dict["FZZ"]=1;
	
	//映射的访问 
	
	dict["XY"] =2;
	cout<<"FZZ in the class "<<dict["FZZ"]<<endl;
	
	
	//查找关键字
	//有返回1,无返回0 
	if(dict.count("XY")){
	cout<<"XY in the class "<<dict["XY"]<<endl;		 
	}
	else{
		cout<<"XY have no class !"<<endl;
	}
	
	
	
	//遍历映射
	//first 表示key,second 表示value 
	for(map<string,int>::iterator it=dict.begin();it!=dict.end();++it){
		cout<<it->first<<" in the class "<<it->second<<endl;
	} 
	
	//清空 
	dict.clear();
	
	
	//消除 dict.erase();
	// 个数 dict.size() ;
	
	
	
	
	 
	
	
	 
	return 0;
}

2.map的简单应用

熟悉map的使用方法和应用

//蒜头君面试
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main() {
	map<int,int>dict;
	int n;
	cin>>n;
	int cnt=1;
	while(n){
		int x;
		cin>>x;
		if(dict.count(x)){
			dict[x]=dict[x]+1;
		}
		else
		dict[x]=cnt;
		n--;
	}
	int max=1;
	int tos=0;
	for(map<int,int>::iterator it=dict.begin();it!=dict.end();it++){
		if(it->second>max)
		{
			max=it->second;
			tos=it->first;
		}
		if(it->second==max){
			if(it->first>tos){
				tos=it->first;
			}
	    }
	}
	cout<<tos<<" "<<max<<endl;
	return 0;
	
}

3.二维map的操作

1.三项参数,使用二维map的思想

2.内外迭代器的使用

重点

//水果店
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main(){
	//定义二维map
	 
	map<string,map<string,int> > dict;
	int n;
	cin>>n;
	while(n){
		string str1,str2;
		int num;
		cin>>str1>>str2>>num;
		//小便利
		 
		dict[str2][str1]+=num;	
        n--;
	}
	
	//外迭代器
	 
	map<string,map<string,int> >::iterator it;
	
	//内迭代器
	 
	map<string ,int>::iterator it2;
	
	for(it=dict.begin();it!=dict.end();it++){
		cout<<it->first<<endl;
		//内迭代器的遍历 
		for(it2=it->second.begin();it2!=it->second.end();it2++){
			cout<<"   |----"<<it2->first<<"("<<it2->second<<")"<<endl;
		} 
		
	} 
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值