C++ map容器

#include<map>

map容器是一个键值对(key-value)映射,key和value可以是任意的类型

通常用于类型之间的映射问题

声明方法:map<key_type,value_type> name;
ex:
map<long,bool>vis;
map<string,int>hash;
map<pair<int,int>,vector<int>> test;

内置函数;

size / empty / clear   //元素个数、判空、清空

begin / end               //首尾迭代器

insert / erase            //插入和删除

insert的参数是pair<key_type,value_type>

erase的参数是迭代器

find

h.find(x)是在变量名为h的map中查找key值为x的二元组,返回指向二元组的迭代器;若没找到,返回h.end()

#include<map>
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
	map<int,int>h;
	h.insert(make_pair(1,2));
	h.insert(make_pair(3,4));
	
	map<int,int>::iterator it;
	
	it=h.find(3);
	cout<<"map容器h中3对应的的值为:";
	cout<<it->second<<endl<<endl;
	
	cout<<"遍历map容器h:"<<endl; 
	h[100]=999;
	for(it=h.begin();it!=h.end();it++)
		cout<<it->first<<' '<<it->second<<endl;
	cout<<endl;
	
	it=h.begin();
	pair<int,int>p=*it;
	h.erase(it);	
	cout<<"删除map容器h的第一个键值对:"<<endl;
	cout<<p.first<<' '<<p.second<<endl<<endl;
	
	cout<<"map容器h的元素个数为:"<<h.size()<<endl; 
	return 0;
}

[]操作符

h[key]返回key映射到的value的引用

可以很方便的通过h[key]来得到key对应的value值,还可以对h[key]进行赋值操作,来改变key对应的value

如果查找的key不存在,执行h[key]后,则会新建一个二元组<key,zero>,并返回zero的引用,zero代表0值

经典使用:

统计单词(字符串)出现的次数:

#include<map>
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
	int n,m;
	cin>>n>>m;
	string str;	
	map<string,int>h;
	
	for(int i=0;i<n;i++){
		cin>>str;
		h[str]++;
	}	
	
	for(int i=0;i<m;i++){
		cin>>str;
		if(h.find(str)==h.end())
			printf("0\n");
		else 
			printf("%d\n",h[str]);
	}

	return 0;
}
/*
8 3
she is a girl
he is a boy

she
am 
a
*/

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值