#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;
}