set、multiset容器
- set和multiset基于红黑树,自动排序
- set中元素不可以重复,multiset中元素可以重复,都在<set>头文件中
- 提供迭代器,但是不能通过迭代器改变值,否则破坏了规则,如果需要改变,先删除在添加。
- insert() 插入数据
set容器构造
- set<T> setT; //默认构造
- multiset<T> multisetT; //默认构造
- set(const set& setT) //拷贝构造
set容器赋值
- set& operator=(const set& setT) //重载=操作符
- swap() //交换容器的元素
set容器大小
- size() //返回容器中元素的个数
- empty() //判断容器是否为空
set容器插入和删除
- insert(element) //插入元素
- clear() //删除所有元素
- erase(pos) // 删除pos位置的元素 ,返回下一个元素的迭代器
- erase(begin,end) // 删除begin和end 之间的元素,返回下一个元素的迭代器
- erase(element) //删除容器中 element 元素
set容器查找操作
- find(element) // 查找element 元素, 返回该元素的迭代器
- lower_bound(element) //返回第一个>= element的元素的迭代器
- upper_bound(element) //返回第一个 > element的元素的迭代器
- equal_range() // 返回lower_bound 和upper_bound两个值(pair类型)
set<int> set1;
set1.insert(1);
set1.insert(3);
set1.insert(11);
set1.insert(5);
set1.insert(9);
pair <set<int>::iterator, set<int>::iterator> mypair;
mypair = set1.equal_range(3);
cout << *(mypair.first) << endl;
cout << *(mypair.second) << endl;
结果:3 5
pair 对组
- 将两个不同的数据类型合并成一个,通过first second两个变量来访问
- 三种构造方式
1.
pair<int,string> pair1(1,"julain");
cout << pair1.first << endl;
cout << pair1.second << endl;
2. pair <int string> pair2=make_pair(1,”julian”);
cout << pair2.first << endl;
cout << pair2.second << endl;
3. pair <int string> pair3=pair2;
set容器更改默认排序方式
-
使用仿函数,定义如下:
class MyCompare
{
Public:
bool operator()( Person p1, Person p2) const
{
return 规则 ;// 从大到小
}
}; -
申明set容器 set<Person, Mycompare> set1; //将会以Mycompare的规则排序
#include "stdafx.h"
#include <iostream>
#include <string>
#include <set>
using namespace std;
class Person
{
public:
Person(int age, int height) :m_age(age), m_height(height)
{
}
int m_age;
int m_height;
};
//仿函数定义的规则
class MyCompare
{
public:
bool operator()( Person p1, Person p2) const
{
return (p1.m_age+p1.m_height) > (p2.m_age + p2.m_height);// 从大到小
}
};
void print(const set<Person, MyCompare>& set1)
{
for (set<Person, MyCompare>::iterator it = set1.begin(); it != set1.end(); it++)
{
cout << (*it).m_age << " " << (*it).m_height << endl;
}
}
int main()
{
Person p1(10, 20), p2(10, 21), p4(10, 22), p3(10, 23);
set<Person, MyCompare> set1; //指定了规则,按照age排序
set1.insert(p1);
set1.insert(p2);
set1.insert(p3);
set1.insert(p4);
print(set1);
// Person p5(11,19); //根据规则,和p1一样,所以没插进去
Person p5(11,100);
set1.insert(p5);
set<Person, MyCompare>::iterator it=set1.find(p5);//查找 按照规则来查找 找m_age+m_height=111的对象
cout << (*it).m_age << " " << (*it).m_height << endl;
return 0;
}