官术网_书友最值得收藏!

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
主站蜘蛛池模板: 武平县| 建瓯市| 始兴县| 金华市| 慈溪市| 突泉县| 临安市| 静乐县| 玛多县| 墨竹工卡县| 岳普湖县| 内江市| 庆阳市| 崇阳县| 阜康市| 焦作市| 克什克腾旗| 绥阳县| 临汾市| 崇明县| 广南县| 芦溪县| 仁布县| 宁国市| 丹江口市| 花莲市| 塘沽区| 甘德县| 稷山县| 宁海县| 永定县| 确山县| 綦江县| 普安县| 江津市| 宜黄县| 梅河口市| 文登市| 皋兰县| 兴业县| 江陵县|