STL::set

1,set:  Sets are containers that store unique elements following a specific order。集合里面的元素不能修改,只能访问,插入或者删除。内部由二叉搜索树来实现(binary search trees);默认排序为:数字从小到大的顺序,可通过传入函数指针或者函数对象来修改排序规则。

Iterators

begin:

end:

rbegin:

rend:

cbegin(c++11):

cend(c++11):

crbegin(c++11):

crend(c++11):

Capacity

empty:

size:

max_size:

Modifiers

insert:

erase:

swap:

clear:

emplace(c++11):

emplace_hint(c++11): hint(暗示):和 emplace 作用基本一致,首先假定一个插入位置,反正插入后还需要根据默认的排序函数进行排序,这样假定一个位置的作用当插入点就是这个位置或者离这个位置很近时可以提升查找插入位置的效率。

Observers:(还未搞懂怎么用。。。)

key_comp:

value_comp:

Operations

find: 在 set 中按值查找元素,找到返回该值的迭代器(双向迭代器),找不到返回 set.end()。

count: 查找 set 中和传入的值相同元素的个数,因为 set 中元素不会重复,所以返回值只能为 1 或者为 0;

lower_bound: 返回一个 大于等于 val 的迭代器(双向迭代器)

upper_bound: 返回一个 大于等于 val 的再向后移动一个位置(和 low_bound 的区别)的迭代器(双向迭代器)

equal_range: 返回一个 pair, 是一个包含所有和 val 相等元素的范围(pair.first 类似 low_bound,pair.second 类似 upper_bound)。用法如下例:

 1 // set::equal_elements
 2 #include <iostream>
 3 #include <set>
 4 
 5 int main ()
 6 {
 7   std::set<int> myset;
 8 
 9   for (int i=1; i<=5; i++) myset.insert(i*10);   // myset: 10 20 30 40 50
10 
11   std::pair<std::set<int>::const_iterator,std::set<int>::const_iterator> ret;
12   ret = myset.equal_range(30);
13 
14   std::cout << "the lower bound points to: " << *ret.first << '\n';  //30
15   std::cout << "the upper bound points to: " << *ret.second << '\n';  //40
16 
17   return 0;
18 }
View Code

补充问题:如何改变 set 中元素的(自定义)排列顺序?

 1 // set::key_comp
 2 #include <iostream>
 3 #include <set>
 4 using namespace std;
 5 
 6 bool greaters(int a,int b){
 7     return a>=b; 
 8 }
 9 
10 int main(){
11     set<int,bool(*)(int,int)> myset(greaters); // 传递函数指针 
12     set<int,bool(*)(int,int)>::iterator it;
13     myset.insert(1);
14     myset.insert(2);
15     myset.insert(3);
16     for(it=myset.begin();it!=myset.end();it++)
17         cout<<' '<<*it;  // 3 2 1 
18     return 0;
19 } 
View Code

reference:

https://blog.csdn.net/gasdfrewqq/article/details/25309675

https://blog.csdn.net/lv1224/article/details/79789638

https://blog.csdn.net/lishuhuakai/article/details/51404214

note: set 不支持 operater [ ],at() 形式的访问元素,只能通过迭代器进行访问。

猜你喜欢

转载自www.cnblogs.com/zpcoding/p/10334898.html