// Demonstrating use of set STL template #include #include #include #include // when the STL types get complicated, typedef them // and use the typedef names where you need them typedef set > integer_set; typedef set >::iterator integer_set_ptr; void show_int (int i) { cout << i << " " ; } void display_collection (const integer_set &d, string title) { cout << title << ": { "; for_each(d.begin(), d.end(), show_int); cout << "}" << endl; } void display_collection (const list &d, string title) { cout << title << ": [ "; for_each(d.begin(), d.end(), show_int); cout << "]" << endl; } int main() { cout << "Demonstrating How Sets Work." << endl; list list2; integer_set set1; // populating the list using "push_back" list2.push_back(89); list2.push_back(99); list2.push_back(89); list2.push_back(69); list2.push_back(59); list2.push_back(89); list2.push_back(89); list2.push_back(49); // list can have duplicates display_collection(list2, "List 2"); list::iterator lp; // insert values from list2 into set1 for (lp = list2.begin(); lp != list2.end(); lp++) set1.insert(*lp); display_collection(set1, "Set 1"); cout << "Count of numbers > 50 is: " << count_if(set1.begin(), set1.end(), bind2nd(greater(), 50)) << endl; // locating things in a set -- use find algorithm as before // or use "member" function of set template // advantage of set "find" member function -- no need to // provide the iterator range... if (set1.find(89) != set1.end()) cout << "89 is in the set!!" << endl; else cout << "89 is NOT in the set!!" << endl; // use generic find algorithm to accomplish the same goals if (find(set1.begin(), set1.end(), 123) != set1.end()) cout << "123 is in the set!!" << endl; else cout << "123 is NOT in the set!!" << endl; // removing items... set1.erase(89); cout << "After erase: "; if (set1.find(89) != set1.end()) cout << "89 is in the set!!" << endl; else cout << "89 is NOT in the set!!" << endl; }