这次先看例子程序:
#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_iterator<int>(cout," ")); cout << endl; // remove all elements up to element with value 3 coll2.erase (coll2.begin(), coll2.find(3)); cout<<"after coll2.erase (coll2.begin(), coll2.find(3)) :"<<endl; // print all elements copy (coll2.begin(), coll2.end(),ostream_iterator<int>(cout," ")); // remove all elements with value 5 int num; num = coll2.erase (5); cout<<"after :num = coll2.erase (5) :"<<endl; cout <<endl<< num << " element(s) removed" << endl; // print all elements copy (coll2.begin(), coll2.end(),ostream_iterator<int>(cout," ")); cout << endl; } /******************* 程序运行结果如下: typedef set<int,greater<int> > IntSet 由大到小: 6 5 4 3 2 1 4 already exists 512 inserted as element 1 after pair<IntSet::iterator,bool> status = coll1.insert(4 and 512): 512 6 5 4 3 2 1 after set<int> coll2(coll1.begin(),coll1.end()) coll2: 由小到大: 1 2 3 4 5 6 512 after coll2.erase (coll2.begin(), coll2.find(3)) : 3 4 5 6 512 after :num = coll2.erase (5) : 1 element(s) removed 3 4 6 512 Process returned 0 (0x0) execution time : 0.496 s Press any key to continue. ********************/