在C ++ STL(标准模板库)中Set集合
Set数据结构
Set集合是一个有序的容器(插入后始终对条目进行排序),可以根据每个条目进行插入和删除。它是一个关联容器,只能用于容纳唯一元素。
主要设置操作是(基本ADT操作)...
insert(Tdata):插入要设置的数据
erase(constTdata):从集合中删除数据
boolempty():检查设置是否为空
find(constTdata):查找数据是否存在于集合中
其中,T是数据类型(int/char/float等。)
STL
标准模板库(STL)是一组C++模板类,用于提供常见的编程数据结构和功能,例如列表,堆栈,数组,集合等。因此,也可以在STL的帮助下实现集合。
STL中的堆栈
声明数据类型T的堆栈:
set<T> st; //基本STL声明
e.g.:
set<int> st; //设置为仅容纳整数声明集合迭代器
set<T> :: iterator it;
e.g.:
set<int>::iterator it;STL集上可用的函数
insert(Tdata):插入要设置的数据。
erase(constTdata):从集合中删除数据。
empty():检查集合是否为空。
find(constTdata):查找数据是否存在于集合中。
size():返回集合的大小。
clear():清除整个集合。
lower_bound(Tdata):将迭代器返回到等效于data或绝对不在集合中的元素data之前的第一个元素。
upper_bound(Tdata):将迭代器返回到等效于data的第一个元素,或者绝对不会超出集合中的element数据。
emplace(Tdata):仅当数据基于集合中已存在的元素是唯一的时才插入数据。
请单击每个功能以检查每个功能的详细代码和实现,以下是最需要的总集合操作的集合。
#include <bits/stdc++.h>
using namespace std;
void printSet(set<int> st){
set<int>:: iterator it;
cout<<"Set contents are:\n";
for(it=st.begin();it!=st.end();it++)
cout<<*it<<" ";
cout<<endl;
}
int main(){
cout<<"Example of set STL\n";
set<int> st;
set<int>:: iterator it;
cout<<"inserting 4\n";
st.insert(4);
cout<<"inserting 6\n";
st.insert(6);
cout<<"inserting 10\n";
st.insert(10);
printSet(st); //打印当前设置
cout<<"erasing 6..\n";
st.erase(6); //原型1-
cout<<"After erasing 6...\n";
printSet(st);
cout<<"erasing first element of the set now\n";
st.erase(st.begin());//原型2-
cout<<"after erasing first element of set now\n";
printSet(st);
if(st.empty()) //检查是否为空
cout<<"Set is empty\n";
else
cout<<"Set is not empty\n";
st.clear(); //清除设置
cout<<"Clearing the set\n";
if(st.empty())
cout<<"Set is empty\n";
else
cout<<"Set is not empty\n";
return 0;
}输出结果
Example of set STL inserting 4 inserting 6 inserting 10 Set contents are: 4 6 10 erasing 6.. After erasing 6... Set contents are: 4 10 erasing first element of the set now after erasing first element of set now Set contents are: 10 Set is not empty Clearing the set Set is empty