- Mastering C++ Programming
- Jeganathan Swaminathan
- 224字
- 2021-07-02 18:28:51
Set
A set container stores only unique values in a sorted fashion. A set organizes the values using the value as a key. The set container is immutable, that is, the values stored in a set can't be modified; however, the values can be deleted. A set generally uses a red-black tree data structure, which is a form of balanced BST. The time complexity of set operations are guaranteed to be O ( log N ).
Let's write a simple program using a set:
#include <iostream>
#include <set>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main( ) {
set<int> s1 = { 1, 3, 5, 7, 9 };
set<int> s2 = { 2, 3, 7, 8, 10 };
vector<int> v( s1.size() + s2.size() );
cout << "\nFirst set values are ..." << endl;
copy ( s1.begin(), s1.end(), ostream_iterator<int> ( cout, "\t" ) );
cout << endl;
cout << "\nSecond set values are ..." << endl;
copy ( s2.begin(), s2.end(), ostream_iterator<int> ( cout, "\t" ) );
cout << endl;
auto pos = set_difference ( s1.begin(), s1.end(), s2.begin(), s2.end(), v.begin() );
v.resize ( pos - v.begin() );
cout << "\nValues present in set one but not in set two are ..." << endl;
copy ( v.begin(), v.end(), ostream_iterator<int> ( cout, "\t" ) );
cout << endl;
v.clear();
v.resize ( s1.size() + s2.size() );
pos = set_union ( s1.begin(), s1.end(), s2.begin(), s2.end(), v.begin() );
v.resize ( pos - v.begin() );
cout << "\nMerged set values in vector are ..." << endl;
copy ( v.begin(), v.end(), ostream_iterator<int> ( cout, "\t" ) );
cout << endl;
return 0;
}
The output can be viewed with the following command:
./a.out
The output of the program is as follows:
First set values are ...
1 3 5 7 9
Second set values are ...
2 3 7 8 10
Values present in set one but not in set two are ...
1 5 9
Merged values of first and second set are ...
1 2 3 5 7 8 9 10
推薦閱讀
- Mastering Entity Framework Core 2.0
- Mastering Natural Language Processing with Python
- HTML5+CSS3基礎(chǔ)開(kāi)發(fā)教程(第2版)
- 網(wǎng)頁(yè)設(shè)計(jì)與制作教程(HTML+CSS+JavaScript)(第2版)
- 教孩子學(xué)編程:C++入門圖解
- Protocol-Oriented Programming with Swift
- Mastering Linux Security and Hardening
- C語(yǔ)言程序設(shè)計(jì)與應(yīng)用(第2版)
- FFmpeg開(kāi)發(fā)實(shí)戰(zhàn):從零基礎(chǔ)到短視頻上線
- Java Web應(yīng)用開(kāi)發(fā)給力起飛
- Vue.js 3應(yīng)用開(kāi)發(fā)與核心源碼解析
- MongoDB Cookbook(Second Edition)
- 分布式數(shù)據(jù)庫(kù)HBase案例教程
- Getting Started with the Lazarus IDE
- Windows 10 for Enterprise Administrators