前言:
STL是C++中的标准库之一,主要由迭代器,算法,容器,仿函数,内存配置器和配接器留部分组成,可以帮助程序员完成许多功能完善,形式多样的程序,而这在ACM竞赛中,STL也因此成为了AC利器
我们这几篇博文都主要讲解一下STL的容器:
set简介
set是集合的意思,是一个内部自动排序且不重复的一个容器,可以用来自动去重和排序,其内部是依靠“红黑树”来实现的
set使用方法
//首先添加set的头文件
#include <set>
using namespace std;
//定义set
set< typename >name;
//typename可以是任何基本容器
set常用命令
方法 | 功能 |
---|---|
insert() | 插入一个元素 |
erase() | 删除一个元素 |
count() | 判断元素是否在set中 |
size() | 获取元素个数 |
clear() | 清空 |
删除元素的三种方法:
erase(iterator)
删除迭代器指向的值erase(first,second)
删除迭代器first和second之间的值erase(value)
删除指定value的值
set中的二分:
lower_bound(value)
返回第一个大于等于value的迭代器upper_bound(value)
返回最后一个大于等于value的迭代器
set示例
#include<bits/stdc++.h>
using namespace std;
set <string> s;
int main(){
//插入元素
s.insert("hello world");
//{"hello world"}
s.insert("hello java");
//{"hello world","hello java"}
s.insert("hello cpp");
//{"hello world","hello java","hello cpp"}
s.insert("hello python");
//{"hello world","hello java","hello cpp","hello python"}
s.insert("hello python");
//{"hello world","hello java","hello cpp","hello python"}
//因为set是自动去重的,所以重复插入不会有变化
//删除元素No.1
s.erase("hello world");
//{"hello java","hello cpp","hello python"}
s.erase("hello ruby");
//{"hello java","hello cpp","hello python"}
//因为"hello ruby"不存在于该set中,所以不做任何改变
//删除元素No.2
set<string>::iterator it;
it=s.begin();
s.erase(it);
//{"hello java","hello python"}
//"hello cpp"排在最前面(字典序),所以被删掉了
//删除元素No.3
set<string>::iterator first,second;
first=s.begin();
second=s.begin();
second++;
s.erase(first,second);
//{"hello python"}
//first,second区间左开右闭
//迭代器的使用
set<string>i;
for (i=s.begin();i!=s.end();i++){
cout<<*i<<endl;
}
//output:hello python
//重新插入元素
set<int>number;
for (int i=1;i<=9;i++)
number.insert(i);
//{1,2,3,4,5,6,7,8,9}
cout<<*number.lower_bound(6)<<endl;
//output:6
cout<<*number.lower_bound(8)<<endl;
//output:8
cout<<*number.upper_bound(6)<<endl;
//output:7
return 0;
}
作者:NorthCity1984
出处:https://grimoire.cn/algorithm/stl-set.html
版权:本文《STL的神奇容器之set》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
出处:https://grimoire.cn/algorithm/stl-set.html
版权:本文《STL的神奇容器之set》版权归作者所有
转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任