set/multisite容器
set/multisite容器的特性是所有元素会根据元素的值自动进行排序。set/multisite容器是关联容器
set底层机制为RB-tree(红黑树,平衡二叉树的一种)。其查找效率非常高,set不允许有重复元素,multisite允许有重复元素
set容器会自动进行排序,所以只提供了insert方法添加数据
不可以通过set的迭代器改变元素的值
#include<iostream>
#include<set>
using namespace std;
void PrintSet(set<int> s) {
for (set<int>::iterator it = s.begin(); it != s.end(); it++) {
cout << (*it) << " ";
}
cout << endl;
}
void SetTest1() {
set<int> s1;
s1.insert(56);
s1.insert(89);
s1.insert(12);
s1.insert(2);
PrintSet(s1);
set<int> s2 = s1;
set<int> s3 = { 10,56,44,23 };
s3.swap(s2);
s1.erase(s1.begin());
s1.erase(89);
PrintSet(s1);
PrintSet(s2);
PrintSet(s3);
}
void SetTest2() {
set<int> s1 = { 10,56,44,23 };
set<int>::iterator it = s1.find(23);
if (it != s1.end()) {
cout << "容器中存在:" << (*it) << endl;
}
else {
cout << "不存在!" << endl;
}
it = s1.lower_bound(25);
if (it != s1.end()) {
cout << "容器中第一个大于等于25的数为:" << (*it) << endl;
}
else {
cout << "容器中所有数都小于25" << endl;
}
pair<set<int>::iterator,set<int>::iterator> myret = s1.equal_range(23);
if (myret.first != s1.end()) {
cout << "容器中第一个大于等于25的数为:" << *(myret.first) << endl;
}
else {
cout << "容器中所有数都大于25" << endl;
}
if (myret.second != s1.end()) {
cout << "容器中第一个大于25的数为:" << *(myret.second) << endl;
}
else {
cout << "容器中所有数都小于等于25" << endl;
}
}
int main() {
SetTest2();
return 0;
}
对组
对组(pair)将一对值组合成一个值,这一对值可以具有不同的数据类型,两个值可以分别用pair的共有函数first和second访问
类模板
template<class T1 , class T2> struct pair
void PairTest() {
pair<string, int> pair1("Leslie",45);
cout << pair1.first << "'s age is " << pair1.second << endl;
pair<string, int> pair2 = make_pair("Bob", 26);
cout << pair2.first << "'s age is " << pair2.second << endl;
pair<string, int> pair3 = pair2;
}
class MyCompare {
public:
bool operator()(int v1, int v2)const
{
return v1 > v2;
}
};
void SetTest3() {
set<int, MyCompare> s1;
s1.insert(56);
s1.insert(89);
s1.insert(12);
s1.insert(2);
for (set<int>::iterator it=s1.begin(); it != s1.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
自定义类与set容器
#include<iostream>
#include<set>
using namespace std;
class Person {
public:
int mId;
int mAge;
Person(int id, int age) : mId(id), mAge(age) {}
Person(){}
};
class PersonRank {
public:
bool operator()(Person p1, Person p2) const
{
return p1.mAge > p2.mAge;
}
};
void SetTest5() {
set<Person, PersonRank> sp;
Person p1(10, 15), p2(11, 19), p3(45, 88);
sp.insert(p1);
sp.insert(p2);
sp.insert(p3);
for (set<Person>::iterator it = sp.begin(); it != sp.end(); it++) {
cout << "年龄:" << (*it).mAge << " ID:" << (*it).mId << endl;
}
Person p4(20, 15);
set<Person>::iterator ret=sp.find(p4);
if (ret == sp.end()) {
cout << "没有找到" << endl;
}
else {
cout << "年龄:" << (*ret).mAge << " ID:" << (*ret).mId << endl;
}
}
int main() {
SetTest5();
return 0;
}