C++STL common operations set articles
Introduction:
#include<set>
1. Unique element
2. Sort
Set is also a container often used in C++, and set is a collection. A set is a collection, so of course its internal elements are unique (non-repeatability of the collection). And the elements in the set are still sorted. Set, like map, is a data structure based on red-black trees.
1. Structure
set<int> s;
s.insert(3);
s.insert(2);
s.insert(4);
s.insert(1);
s.insert(1);
s.insert(1);
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << endl;
We can see that after inserting int data 3, 2, 4, 1, 1, 1 in the constructed set s, the traversal output results are 1, 2, 3, 4. This also shows that the set does not allow duplicate elements, and is sorted.
2. Commonly used functions
set<int> s;
s.insert(3);
s.insert(2);
s.insert(4);
s.insert(1);
cout << *s.begin() << endl; //返回set的第一个元素的迭代器
cout << *(--s.end()) << endl; //返回set最后一个元素后面一个位置的迭代器
if (s.empty()) //判断set是否为空
cout << "is empty" << endl;
else
cout << "is not empty" << endl;
cout << s.size() << endl; //输出set此时的元素个数
s.clear(); //清空,删除所有元素
cout << s.size() << endl;
operation result:
set<int> s;
s.insert(3);
s.insert(1);
s.insert(1);
cout << s.count(1) << endl;
cout << s.count(2) << endl;
Count is used to count the number of occurrences of a key value. Since set and map do not allow duplicate data to appear, the return value of count can only be 0 or 1 (existing or non-existing in the set).
set<int> s;
s.insert(3);
s.insert(2);
auto it = s.find(1);
if (it != s.end())
cout << "YES" << endl;
else
cout << "NO" << endl;
it = s.find(3);
if (it != s.end())
cout << "YES" << endl;
else
cout << "NO" << endl;
The find function returns the iterator of the element that needs to be found, or end() if there is none.
3. Delete
#include<iostream>
#include<set>
using namespace std;
int main() {
set<int> s;
s.insert(3);
s.insert(2);
s.insert(4);
s.insert(1);
s.insert(1);
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << endl;
cout << "**********" << endl;
s.erase(1); //给定key值的删除
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << endl;
cout << "**********" << endl;
s.erase(s.begin()); //给定迭代器的删除
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << endl;
cout << "**********" << endl;
s.erase(s.begin(), s.end()); //给定迭代器返回的删除
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << endl;
cout << "**********" << endl;
return 0;
}
Initially, the elements in our set are 1, 2, 3, 4. After deleting the element with the given key 1, the elements in the set are left with 2, 3, 4, and the first of the given iterator set is deleted. After the element (2) corresponding to the position, 3 and 4 are left. After deleting the elements in the given iterator range (from beginning to end), there are no more elements in the set.
set common operations
If you find any problems, please correct me!