C++ Set運用執行個體
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
#include <functional>
using namespace std;
int main()
{
//容器内的元素下降排序
set<int,greater<int>> set1;
set1.insert({6,3,5,1,4,2});
set1.insert(5);
for (int elem:set1)
{
cout << elem << " ";
}
cout << endl;
auto status = set1.insert(4);
if (status.second)
{
cout << "4 inserted as element "<<distance(set1.begin(),status.first)+1 << endl;
}
else
{
cout << "4 already exists" << endl;
}
//容器内的元素升序排序
set<int> set2(set1.cbegin(),set1.cend());
copy(set2.cbegin(),set2.cend(),ostream_iterator<int>(cout," "));
cout << endl;
//移除從第一個元素到 元素3所在位置的元素
set2.erase(set2.begin(),set2.find(3));
//删除所有值為5 的元素
int num;
num = set2.erase(5);
cout << num<<" element(s) removed" << endl;
copy(set2.cbegin(),set2.cend(),ostream_iterator<int>(cout," "));
cout << endl;
system("pause");
return 0;
}
6 5 4 3 2 1
4 already exists
1 2 3 4 5 6
1 element(s) removed
3 4 6
請按任意鍵繼續. . .
代碼參考:C++标準庫(第2版)