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

Code walkthrough

The following code declares and initializes two sets, s1 and s2:

set<int> s1 = { 1, 3, 5, 7, 9 };
set<int> s2 = { 2, 3, 7, 8, 10 };

The following line will ensure that the vector has enough room to store the values in the resultant vector:

vector<int> v( s1.size() + s2.size() );

The following code will print the values in s1 and s2:

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;

The set_difference() algorithm will populate the vector v with values only present in set s1 but not in s2. The iterator, pos, will point to the last element in the vector; hence, the vector resize will ensure that the extra spaces in the vector are removed:

auto pos = set_difference ( s1.begin(), s1.end(), s2.begin(), s2.end(), v.begin() ); 
v.resize ( pos - v.begin() );

The following code will print the values populated in the vector v:

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;

The set_union() algorithm will merge the contents of sets s1 and s2 into the vector, and the vector is then resized to fit only the merged values:

pos = set_union ( s1.begin(), s1.end(), s2.begin(), s2.end(), v.begin() );
v.resize ( pos - v.begin() );

The following code will print the merged values populated in the vector v:

cout << "\nMerged values of first and second set are ..." << endl;
copy ( v.begin(), v.end(), ostream_iterator<int> ( cout, "\t" ) );
cout << endl;
主站蜘蛛池模板: 宜兰市| 马龙县| 乐业县| 喀喇沁旗| 黔东| 泰安市| 土默特右旗| 沧州市| 原阳县| 通州区| 嘉兴市| 蓬溪县| 馆陶县| 无极县| 拜泉县| 五指山市| 阿图什市| 乌拉特前旗| 三河市| 黔西县| 浦县| 太仓市| 阿勒泰市| 乌兰浩特市| 辽宁省| 盱眙县| 苍山县| 田东县| 吉首市| 睢宁县| 渭源县| 霍山县| 瑞金市| 连江县| 电白县| 乌苏市| 山阳县| 海淀区| 鄂伦春自治旗| 海安县| 肇州县|