set/multiset容器
set/multiset的特性是:
所有元素会根据元素的值自动进行排序。Set是以RB-tree(红黑树,平衡二叉树的一种)为底层机制,其查找效率非常好,set容器中不允许重复元素,multiset允许重复元素
set/multiset的各种操作
案例(易懂易学)
该案例配合上面的操作,结合以下代码。
#include<iostream>
#include<set>
#include<list>
using namespace std;
void printSet(set<int>& v) {
for (set<int>::iterator it = v.begin(); it != v.end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
//仿函数
////如何改变默认排序?
class mycompare {
public:
constexpr bool operator()(int v1, int v2) const{
return v1 > v2;
}
};
void test00() {
set<int,mycompare>s1;//自动排序,默认从小到大。
s1.insert(7);
s1.insert(2);
s1.insert(4);
s1.insert(5);
s1.insert(1);
for (set<int>::iterator it = s1.begin(); it != s1.end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
//1-set容器初始化
void test01() {
set<int>s1;//自动排序,默认从小到大。
s1.insert(7);
s1.insert(2);
s1.insert(4);
s1.insert(5);
s1.insert(1);
printSet(s1);//1 2 4 5 7
//赋值操作
set<int>s2;
s2 = s1;
//删除操作
s1.erase(s1.begin());
s1.erase(7);
printSet(s1);//2 4 5
//如何改变默认排序?
}
//2-查找
void test02() {
set < int>s1;
s1.insert(7);
s1.insert(2);
s1.insert(4);
s1.insert(5);
s1.insert(1);
set<int>::iterator ret = s1.find(1);
if (ret == s1.end())
cout << "未找到" << endl;
else {
cout << *ret << endl;//1
}
//找比2等于大于的第一个值,
ret=s1.lower_bound(2);//找比2等于大于的第一个值,如果不存在等于的就找把它大的第一个数
cout << *ret << endl;//2
//找第一个大于key的值
ret = s1.upper_bound(2);
if (ret == s1.end())
cout << "未找到" << endl;
else {
cout << *ret << endl;//4
}
//equal_range 返回Lower_bound和upper_bound;
pair<set<int>::iterator, set<int>::iterator> myset = s1.equal_range(2);
if (myset.first == s1.end())
cout << "未找到" << endl;
else {
cout << *(myset.first) << endl;//2
}
if (myset.second == s1.end())
cout << "未找到" << endl;
else {
cout << *(myset.second) << endl;//4
}
}
class Person {
public:
Person(int age, int id) :id(id), age(age) {}
public:
int id;
int age;
};
class mycompare2 {
public:
bool operator()(Person p1, Person p2) const {
return p1.age > p2.age;
}
};
void test03() {
set<Person, mycompare2>sp;
Person p1(10, 20), p2(30, 40), p3(50, 60);
sp.insert(p1);
sp.insert(p2);
sp.insert(p3);
Person p4(10, 20);
for (set<Person, mycompare2>::iterator it = sp.begin(); it != sp.end(); ++it)
cout << (*it).age << " "<<(*it).id<<endl;
//查找
set<Person,mycompare>::iterator ret=sp.find(p4);
if (ret == sp.end()) {
cout << "未找到" << endl;
}
else {
cout << "ret: " << (*ret).age<<" "<<(*ret).id << endl;
}
}
int main(void) {
//test00();
//test01();
//test02();
test03();
return 0;
}