1、

STL中的关联式容器的共性_ios

代码如下:

/*
 * multiset_1.cpp
 *
 *  Created on: 2013年8月6日
 *      Author: Administrator
 */

#include <iostream>
#include <set>
using namespace std;

template<typename T>
void print(T b, T e, char c = ' ') {
	while (b != e) {
		cout << *b++ << c;
	}
}

struct Person {
	string name;
	int age;
public:
	Person(string n, int a) :
			name(n), age(a) {

	}
};

bool operator<(const Person& a, const Person& b) {
	return a.age < b.age;
}

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

int main() {
	multiset<Person> mp;
	mp.insert(Person("liuyifei", 21));
	mp.insert(Person("刘亦菲", 18));
	mp.insert(Person("liushishi", 19));
	mp.insert(Person("liuyifei", 21));
	mp.insert(Person("liuyifei", 21));
	mp.insert(Person("刘诗诗", 22));
	mp.insert(Person("刘亦菲", 18));
	mp.insert(Person("liushishi", 19));
	mp.insert(Person("allen", 21));
	mp.insert(Person("liuyifei", 21));
	mp.insert(Person("刘亦菲", 18));
	mp.insert(Person("刘诗诗", 22));
	mp.insert(Person("刘亦菲", 18));
	mp.insert(Person("liushishi", 19));
	print(mp.begin(), mp.end());

	multiset<Person>::iterator it = mp.find(Person("allen", 21));
	if (it == mp.end()) {
		cout << "没有找到allen" << endl;
	} else {
		cout << "发现目标:" << *it << endl;
	}

	it = mp.find(Person("章泽天", 21));
	if (it == mp.end()) {
		cout << "没有找到章泽天" << endl;
	} else {
		cout << "发现目标:" << *it << endl;
	}

	it = mp.find(Person("刘诗诗", 18));
	cout << mp.count(*it) << "个" << *it << endl;

	it = mp.find(Person("liushishi", 19));
	cout << mp.count(*it) << "个" << *it << endl;

	multiset<Person>::iterator ib,ie;
	ib = mp.lower_bound(Person("liuyifei",21));
	ie = mp.upper_bound(Person("liuyifei",21));
	cout<<"============================="<<endl;
	print(ib,ie);
	cout<<"============================="<<endl;
	pair<multiset<Person>::iterator,multiset<Person>::iterator  > p = mp.equal_range(Person("刘亦菲",21));
	print(p.first,p.second);
	typedef multiset<Person>::iterator Iter;
	pair<Iter,Iter> q = mp.equal_range(Person("liushishi",18));
	print(q.first,q.second);
	cout<<"========================"<<endl;
	mp.erase(Person("liuyifei",21));
	mp.erase(Person("刘诗诗",22));
	print(mp.begin(),mp.end());

}



3、结果如下:


刘亦菲:18 刘亦菲:18 刘亦菲:18 刘亦菲:18 liushishi:19 liushishi:19 liushishi:19 liuyifei:21 liuyifei:21 liuyifei:21 allen:21 liuyifei:21 刘诗诗:22 刘诗诗:22 发现目标:liuyifei:21
发现目标:liuyifei:21
4个刘亦菲:18
3个liushishi:19
=============================
liuyifei:21 liuyifei:21 liuyifei:21 allen:21 liuyifei:21 =============================
liuyifei:21 liuyifei:21 liuyifei:21 allen:21 liuyifei:21 刘亦菲:18 刘亦菲:18 刘亦菲:18 刘亦菲:18 ========================
刘亦菲:18 刘亦菲:18 刘亦菲:18 刘亦菲:18 liushishi:19 liushishi:19 liushishi:19