集合
template <class T, class Compare = less<T>, class Alloc = allocator<T> > class set;
< set >
介绍
set是按顺序存储无重复元素的容器。
在set中,一个值标志一个元素,而且每个值都是唯一的。set中元素的值不能被修改,但是可以被插入或删除。
在内部,元素会通过一个比较对象(Compare类型)来按照一个“弱排序准则”按特定顺序排列。
在通过键查找元素方面set要比unordered_set慢(set是用红黑树实现,平均查找为O(lgN),unordered_set用hash实现,平均查找为O(1)),但是优势是可以在子集中通过元素的顺序进行直接的迭代。
sets通常被实现为二叉搜索树。
容器属性
- 关联性
关联容器中的元素通过键来引用,而不是通过在容器中的绝对位置。 - 顺序性
容器中的元素严格按顺序排列,新插入的元素会找到自己的位置。 - 集合性
元素的键也是它的值。 - 唯一性
没有相同键的两个元素。 - 分配器感知
使用分配器对象来动态管理所需内存。
模板参数
- T
元素键的类型,别名set::key_type和set::value_type - Compare
二元谓词的类型,用来比较元素的大小,默认是less< T >,别名set::key_compare和set::value_compare - Alloc
分配器类型,别名set::allocator_type
成员函数
构造函数
/* 默认 */
explicit set(const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type());
/* 范围 */
template <class InputIterator>
set(InputIterator first, InputIterator last, const key_compare& comp = key_compare(), const allocator_type& alloc = allocator_type());
/* 拷贝构造函数 */
set(const set& x);
set(const set& x, const allocator_type& alloc);
/* 移动构造函数 */
set(set&& x);
set(set&& x, const allocator_type& alloc);
/* 初始化列表 */
set(initializer_list<key_type> il, const key_compare& comp = key_compare(), const allocator_type alloc = allocator_type());
// 举例
// constructing sets
#include <iostream>
#include <set>
bool fncomp (int lhs, int rhs) {return lhs<rhs;}
struct classcomp {
bool operator() (const int& lhs, const int& rhs) const
{return lhs<rhs;}
};
int main ()
{
std::set<int> first; // empty set of ints
int myints[]= {10,20,30,40,50};
std::set<int> second (myints,myints+5); // range
std::set<int> third (second); // a copy of second
std::set<int> fourth (second.begin(), second.end()); // iterator ctor.
std::set<int,classcomp> fifth; // class as Compare
bool(*fn_pt)(int,int) = fncomp;
std::set<int,bool(*)(int,int)> sixth (fn_pt); // function pointer as Compare
return 0;
}
迭代器
begin() end() rbegin() rend() cbegin() cend() crbegin() crend()
容量
size()
empty()
max_size()
元素操作
insert()
erase()
swap()
clear()
emplace()
emplace_hint()
find()
count()
lower_bound()
upper_bound()
equal_range()
// 举例
#include <iostream>
#include <set>
#include <utility>
using namespace std;
int main() {
set<int> s;
for (int i = 1; i < 6; i++) s.insert(i * 10);
pair<set<int>::const_iterator, set<int>::const_iterator> it;
it = s.equal_range(29);
cout << *it.first << endl;
cout << *it.second << endl;
return 0;
}
// Output
30
30
其它
key_comp()
value_comp()