【快速入门 C++ STL】 demo 演示七:set/multiset

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

class student
{
public:
	student(int ID,string name)
	{
		this->ID = ID;
		this->name = name;
	}
	int ID;
	string name;
};
//构造仿函数,从大到小排序 
struct stuFunctor
{
	bool operator()(const student &left,const student &right)
	{
		if (left.ID < right.ID) return true;
		else return false;
	}
};
void printFun(set<student, stuFunctor> &obj)
{
	for (set<student, stuFunctor>::iterator it = obj.begin(); it != obj.end(); it++)
	{
		cout << it->ID << " " << it->name << endl;
	}
	cout << endl;
}
int main()
{
	set<student, stuFunctor> set1;
	string str[5] = { "A", "B", "C", "D", "E" };
	for (size_t i = 0; i < 5; i++)
	{
		student obj(i, str[i]);
		set1.insert(obj);
	}
	printFun(set1);

	//判断是否插入成功
	pair<set<student, stuFunctor>::iterator, bool> pair1;
	pair1=set1.insert(student(0, "B"));
	if (pair1.second == false) cout << "插入失败\n";
	else cout << "插入成功\n";
	printFun(set1);
	pair1 = set1.insert(student(5, "B"));	
	if (pair1.second == false) cout << "插入失败\n";
	else cout << "插入成功\n";
	printFun(set1);

	//查找
	student stu(4, "A");
	set<student, stuFunctor>::iterator it0=set1.find(stu);//等于4
	cout << "等于4\t";
	cout << it0->ID << " " << it0->name << endl;

	set<student, stuFunctor>::iterator it1 = set1.lower_bound(stu);//大于等于4
	cout << "大等于4\t" ;
	cout << it1->ID << " " << it1->name << endl;

	set<student, stuFunctor>::iterator it2 = set1.upper_bound(stu);//大于4
	cout << "大于4\t";
	cout << it2->ID << " " << it2->name << endl;

	pair<set<student, stuFunctor>::iterator, set<student, stuFunctor>::iterator> pair2;//等于4和大于4
	pair2 = set1.equal_range(stu);
	cout << "等于4\t" << pair2.first->ID << " " << pair2.first->name << endl;
	cout << "大于4\t" << pair2.second->ID << " " << pair2.second->name << endl;

	system("pause");
	return 0;
}

multiset和set用法一致,增加了允许重复值

#include<set>
#include<iostream>
using namespace std;
int main(int argc,char** argv)
{
	multiset<int> mulset;
	for (size_t i = 0; i < 5; i++)
	{
		mulset.insert(i);
	}
	mulset.insert(0);
	mulset.insert(1);
	mulset.insert(4);
	printFun(mulset);
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值