STL::set/multiset

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

multiset: 和 set 操作一样,不同点是 key 可以相同。

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() 形式的访问元素,只能通过迭代器进行访问。

 

posted on   爱笑的张飞  阅读(265)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示