Set是一个集合;
集合中有不同的元素;
所有元素会根据value进行排序,默认是升序,即采用operator< 实现比较;
不可以通过迭代器来改变value,即只读;
set插入/删除,迭代器仍然有效,除被删除元素的迭代器除外;(把迭代器想象为一个指针即可);
底层采用红黑树实现。
set的各成员函数列表如下:
-
begin()–返回指向第一个元素的迭代器
-
clear()–清除所有元素
-
count()–返回某个值元素的个数
-
empty()–如果集合为空,返回true
-
end()–返回尾后迭代器
-
equal_range()–返回集合中与给定值相等的上下限的两个迭代器
-
erase()–删除集合中的元素
-
find()–返回一个指向被查找到元素的迭代器
-
get_allocator()–返回集合的分配器
-
insert()–在集合中插入元素
-
lower_bound()–返回指向大于(或等于)某值的第一个元素的迭代器
-
key_comp()–返回一个用于元素间值比较的函数
-
max_size()–返回集合能容纳的元素的最大限值
-
rbegin()–返回指向集合中最后一个元素的反向迭代器
-
rend()–返回指向集合中第一个元素的反向迭代器
-
size()–集合中元素的数目
-
swap()–交换两个集合变量
-
upper_bound()–返回大于某个值元素的迭代器
-
value_comp()–返回一个用于比较元素间的值的函数
// test
#include <set>
#include <algorithm>
typedef set<int, greater<int> > IntSetGreater;
typedef set<int, less<int> > IntSetLess;
int main()
{
int i;
int ia[5] = { 0,1,2,3,4 };
IntSetLess iset(ia, ia + 5);
iset.insert(3); // 由于结合中已有3,所以无变化
cout << "size " << iset.size() << endl;
cout << "3 count = " << iset.count(3) << endl;
iset.insert(5);
cout << "size " << iset.size() << endl;
cout << "3 count = " << iset.count(3) << endl;
iset.erase(1);
cout << "size " << iset.size() << endl;
cout << "3 count = " << iset.count(3) << endl;
cout << "1 count = " << iset.count(3) << endl;
for (auto & i : iset)
{
cout << i << endl;
}
auto iter = find(iset.begin(), iset.end(), 3);
if (iter != iset.end())
cout << "found.\n";
iter = iset.find(1);
if (iter != iset.end())
cout << "found 1" << endl;
参考:《STL源码分析》