// test_set2.cc just demo some features, using 'inserter' #include #include // needed for set_ algorithms #include using namespace std; typedef set my_set; // give my typename to a set of integers // this simplifies code for function prototypes, etc. void put(my_set S) // function to output a set, default order { cout << "S(" << S.size() << ")= "; // use begin() and end() to be safe for(my_set::const_iterator p=S.begin(); p!=S.end(); p++) cout << *p << " "; cout << endl; } int main() { my_set A; // construct an empty sets my_set B; my_set C; my_set D; my_set D1; my_set D2; my_set D3; my_set::const_iterator p; // scratch pointer for 'find' cout << "test_set2 running, S is " << (C.empty() ? "empty" : "has junk") << endl; cout << C.size() << "=size of C, max=" << C.max_size() << endl; A.insert(3); A.insert(5); A.insert(1); B.insert(1); B.insert(2); B.insert(3); cout << "initial A "; put(A); // begin() end() size() used in 'put()' cout << "initial B "; put(B); set_intersection(A.begin(), A.end(), B.begin(), B.end(), inserter(C,C.begin())); cout << "intersection A B "; put(C); set_union(A.begin(), A.end(), B.begin(), B.end(), inserter(D,D.begin())); cout << "union A B "; put(D); set_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(D1,D1.begin())); cout << "difference A-B "; put(D1); set_difference(B.begin(), B.end(), A.begin(), A.end(), inserter(D2,D2.begin())); cout << "difference B-A "; put(D2); set_symmetric_difference(A.begin(), A.end(), B.begin(), B.end(), inserter(D3,D3.begin())); cout << "sym diff A B "; put(D3); cout << "C = D "; C = D; put(C); cout << "first in set " << *D.begin() << endl; D.erase(D.begin()); cout << "erased first "; put(D); p = D.find(3); // remember, it returns a pointer, not a value cout << "D.find(3) found " << *p << endl; p = D.find(4); cout << "D.find(4) " << (p==D.end()? "not found" : "4" /* *i */) << endl; cout << "test_set2 finished" << endl; return 0; } // Output of this program is: // test_set2 running, S is empty // 0=size of C, max=4294967295 // initial A S(3)= 1 3 5 // initial B S(3)= 1 2 3 // intersection A B S(2)= 1 3 // union A B S(4)= 1 2 3 5 // difference A-B S(1)= 5 // difference B-A S(1)= 2 // sym diff A B S(2)= 2 5 // C = D S(4)= 1 2 3 5 // first in set 1 // erased first S(3)= 2 3 5 // D.find(3) found 3 // D.find(4) not found // test_set2 finished