这次先看例子程序:
#include <iostream>
#include <set>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
/* type of the collection:
* - no duplicates
* - elements are integral values
* - descending order
*/
typedef set<int,greater<int> > IntSet;
IntSet coll1; // empty set container
// insert elements in random order
coll1.insert(4);
coll1.insert(3);
coll1.insert(5);
coll1.insert(1);
coll1.insert(6);
coll1.insert(2);
coll1.insert(5);
cout<<"typedef set<int,greater<int> > IntSet 由大到小:"<<endl;
// iterate over all elements and print them
IntSet::iterator pos;
for (pos = coll1.begin(); pos != coll1.end(); ++pos)
{
cout << *pos << ' ';
}
cout << endl;
// insert 4 again and process return value
pair<IntSet::iterator,bool> status = coll1.insert(4);
if (status.second)
{
cout << "4 inserted as element "
<< distance(coll1.begin(),status.first) + 1
<< endl;
}
else
{
cout << "4 already exists" << endl;
}
status = coll1.insert(512);
if (status.second)
{
cout << "512 inserted as element "
<< distance(coll1.begin(),status.first) + 1
<< endl;
}
else
{
cout << "512 already exists" << endl;
}
// print all elements of the copy
cout<<"after pair<IntSet::iterator,bool> status = coll1.insert(4 and 512):"<<endl;
copy (coll1.begin(), coll1.end(),ostream_iterator<int>(cout," "));
cout<<endl;
// assign elements to another set with ascending order
set<int> coll2(coll1.begin(),coll1.end());
cout<<"after set<int> coll2(coll1.begin(),coll1.end()) coll2: 由小到大:"<<endl;
// print all elements of the copy
copy (coll2.begin(), coll2.end(),ostream_ite