c++ STL关联式容器的共性(权哥)

/*关联式容器共性:都是用二叉查找树实现的,都自动根据关键字排序
set<K>,  multiset<K>, map<K,V>, multimap<K,V)
查找:.find(key)返回一个迭代器指向找到的第一个元素,失败返回.end()
统计:.count(key)统计关键字等于key的元素的个数
删除:.erase(key)删除关键字等于key的所有元素
区间:.lower_bound(key)取得关键字为key的第一个元素的位置, .upper_bound(key)取得关键字为key的最后一个元素之后的位置, .equal_range(key)一次取得关键字为key的元素的区间,返回一个pair
插入:.insert(element)
构造函数:可以用比较函数作为参数bool(*compare)(K a,K b)
*/
#include <set>
#include <iostream>
using namespace std;
#include "../stl2/print.h"
struct Person{
	string name;
	int age;
public:
	Person(const char* n, int a):name(n),age(a){}
};
bool operator<(const Person& a, const Person& b)
{return a.age<b.age||a.age==b.age&&a.name<b.name;}

ostream& operator<<(ostream&o, const Person& x)
{return o<<x.name<<':'<<x.age;} 

int main()
{
	multiset<Person> mp;
	mp.insert(Person("ZYP",26));
	mp.insert(Person("GYR",18));
	mp.insert(Person("YLB",20));
	mp.insert(Person("ZYP",26));
	mp.insert(Person("ZYP",26));
	mp.insert(Person("WCB",21));
	mp.insert(Person("GYR",18));
	mp.insert(Person("YLB",20));
	mp.insert(Person("ZHM",22));
	mp.insert(Person("ZYP",26));
	mp.insert(Person("GYR",18));
	mp.insert(Person("WCB",21));
	mp.insert(Person("GYR",18));
	mp.insert(Person("WCB",21));
	mp.insert(Person("GYR",18));
	print(mp.begin(), mp.end());
	multiset<Person>::iterator it=mp.find(Person("ZHM",22));
	if(it==mp.end()) cout << "没有找到ZHM" << endl;
	else cout << "发现目标:" << *it << endl;
	it=mp.find(Person("FR",22));
	if(it==mp.end()) cout << "没有找到FR" << endl;
	else cout << "发现目标:" << *it << endl;
	it = mp.find(Person("GYR",18));
	cout << mp.count(*it) << "个" << *it << endl;
	it = mp.find(Person("ZYP",26));
	cout << mp.count(*it) << "个" << *it << endl;
	multiset<Person>::iterator ib, ie;
	ib = mp.lower_bound(Person("WCB",21));
	ie = mp.upper_bound(Person("WCB",21));
	cout << "===================" << endl;
	print(ib, ie);
	cout << "===================" << endl;
	pair<multiset<Person>::iterator,multiset<Person>::iterator>p=mp.equal_range(Person("YLB",20));
	print(p.first,p.second);
	typedef multiset<Person>::iterator Iter;
	pair<Iter,Iter>q=mp.equal_range(Person("GYR",18));
	print(q.first,q.second);
	cout << "===================" << endl;
	mp.erase(Person("GYR",18));
	mp.erase(Person("ZYP",26));
	print(mp.begin(), mp.end());
}
/*运行结果:
GYR:18 GYR:18 GYR:18 GYR:18 GYR:18 YLB:20 YLB:20 WCB:21 WCB:21 WCB:21 ZHM:22 ZYP:26 ZYP:26 ZYP:26 ZYP:26 
发现目标:ZHM:22
没有找到FR
5个GYR:18
4个ZYP:26
===================
WCB:21 WCB:21 WCB:21 
===================
YLB:20 YLB:20 
GYR:18 GYR:18 GYR:18 GYR:18 GYR:18 
===================
YLB:20 YLB:20 WCB:21 WCB:21 WCB:21 ZHM:22 
*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值