C++ 关联容器总结

关联容器
关联容器共享大部分——但不是全部——顺序容器的操作。关联容器不提供front, push_front, pop_front, back, push_back, pop_back等操作。
一、map和set类型
1、关联容器的类型
(1)map定义的类型:
map<string,int>::key_type;		//键的类型 const string
map<string,int>::mapped_type;	//值得类型 Int
map<string,int>::value_type;	//map所存元素的类型 pair<const string,int>类型
map的键类型key_type必须支持<操作符。(元素按顺序存放)
(2)set定义的类型
在set容器中,存储的元素类型(value_type)不是pair类型,而与key_type相同的类型。与map类型一样,set容器存储的键也必须是唯一的,而且不能修改。
2、map对象的定义(set类型的定义和使用除了不支持下标操作和存储的类型不同以外,其他的一样。这里不做具体介绍
map<string ,int> m;
map<string,int> m(m2);
map<string,int> m(b,e);

map<string,int>::iterator ite = m.begin();
ite->first = "hwl";            //error:key is const

set<string> s;
set<string> s(s2);
set<string> s(b.e);
3、 map类型的访问
(1)下标访问
m["hwl"];				//m中没有键值为hwl的添加一个,采用值初始化方式初始化值。有的话访问m的值。
						//典型的用法:统计词频
string wrods;
map<string,int> words_count;
while (cin>>words)
{
	++words_count[words];
}
(2)使用count检查map对象中某键是否存在(0 / 1)
int occurs = 0;
if (words_count.count("hwl"))
{
	occurs = words_count["hwl"];
}
两次查找map中的元素效率低。
(3)find查找map中的元素(返回元素迭代器 / end迭代器)
int occurs = 0;
map<string,int>::iterator ite = words_count.find("hwl");
if (ite != words_count.end())
{
	occurs = ite->second;
}
4、map对象和set对象添加元素
map<string,int>words;
set<string> keys;
//...1
pair<map<string,int>::iterator,bool> re = wrods.insert(map<string,int>::value_type("hwl",1));
pair<map<string,int>::iterator,bool> re = wrods.insert(make_pair("hwl",1));
pair<set<string>::iterator,bool> re = keys.insert("hwl");
//...2
wrods.insert(b,e);
keys.insert(b,e);
//...3
words.insert(ite,value_type);
5、map对象删除元素
map<string,int> words;		
words.erase("hwl");		//返回size_type类型(0 / 1)
words.erase(ite);		//返回void,ite所指的元素必须存在
words.erase(b,e);		//返回void
二、multimap和multiset类型
multimap和multiset所支持的操作分别于map和set的操作相同,只有一个例外:multimap不支持下标运算。(因为一个键对应多个值)为了顺应一个键对应多个值这一性质,map和multimap,set和multiset中相同的操作都以不同的方式做出了一定修改。
在使用multimap和multiset时,对于某个键,必须做好处理多个值的准备,而非只有单一值。
1、元素的添加和删除
multimap<string,string> authors;
authors.insert(make_pair("hwl","IBNFGMGM"));
authors.insert(make_pair("hwl","IBN123333"));

multimap<string,string>::size_type cnt = authors.erase("hwl");//返回删除的个数
authors.erase(ite);//返回void
authors.erase(b,e);//返回void
2、查找元素
map和set的元素师按顺序存储的。而multimap和multiset也一样。如果某个键对应多个值的话,他们在容器中时相邻存放的。
(1)使用find和count操作
count 统计某个键在容器中出现的次数;
find操作返回指向第一个拥有正在查找的实例的迭代器;
(2)与众不同的解决方案
authors.lower_bound(key);	//返回一个迭代器,指向键不小于key的第一个元素
authors.upper_bound(key);	//返回一个迭代器,指向键大于key的第一个元素
authors.equal_range(key);	//返回一个pair对象第一个元素等价于authors.lower_bound(key),第二个等价于authors.upper_bound(key);
pair<authors::iterator,authors::iterator> pos = authors.equal_range(key);







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值