Set translates to a collection, which is the definition of a container set that is automatically ordered internally and does not contain repeated elements.
set<typename> name;
set<int> vi;
set<double> vi;
set<char> vi;
set<node> vi;//node可以是结构体
set<int> a[100]; //数组里面每个元素都是一个set集合
insert(x) insert x into the set container, and automatically increase sorting and de-duplication
//insert(x) 将x插入set容器中,并自动递增排序和去重
st.insert(4);
st.insert(3);
st.insert(1);
st.insert(2);
//不支持<it.end()的写法
for(set<int>::iterator it=st.begin();it!=st.end();it++){
cout<<*it<<" ";//1 2 3 4
}
The traversal of the set collection
can only be traversed through iterators.
The stl containers other than vector and string do not support the *(it+i) access method.
//不支持<it.end()的写法
for(set<int>::iterator it=st.begin();it!=st.end();it++){
cout<<*it<<" ";//1 2 3 4
}
The elements in the set are automatically sorted in ascending order, and duplicate elements are automatically removed
find(value) returns the iterator with the corresponding value in the set
set<int>::iterator it=st.find(3); //查找值为3的元素返回其迭代器
cout<<*it<<endl; //如果查找的元素不存在会返回最后一个元素的迭代器
erase() delete elements
//erase() 有两种用法一种是删除单个元素另一种是删除一个区间的所有元素
//删除单个的方法又有两种
//1.st.erase(it) it为所删元素的迭代器 可以和find连用
//1 2 3 4
st.erase(st.find(3));
for(set<int>::iterator it=st.begin();it!=st.end();it++){
cout<<*it<<" ";//1 2 4
}
cout<<endl;
//2.st.erase(value) value为所删除元素的值
//1 2 4
st.erase(1);
for(set<int>::iterator it=st.begin();it!=st.end();it++){
cout<<*it<<" ";//2 4
}
cout<<endl;
st.insert(4);
st.insert(3);
st.insert(1);
st.insert(2);
//删除整个区间
//1 2 3 4
st.erase(st.find(2),st.end());
for(set<int>::iterator it=st.begin();it!=st.end();it++){
cout<<*it<<" ";//1
}
size() returns the number of elements in the set
//1 2 3 4
cout<<st.size(); //4
clear() clear all elements in st
st.clear();
cout<<st.size();
empty() Determine whether it is empty
st.clear();
cout<<st.empty()<<endl;//1 true
lower_bound(k)
upper_bound(k)
st.insert(4);
st.insert(3);
st.insert(1);
st.insert(2);
//1 2 3 4
//lower_bound(k) 返回一个迭代器,指向键值不小于k的第一个元素
set<int>::iterator it=st.lower_bound(2);//寻找第一个大于等于2的数
cout<<*it<<endl;//2
//upper_bound(k) 返回一个迭代器,指向键值大于k的第一个元素
it=st.upper_bound(2);
cout<<*it<<endl;//3