// File: STL/vec.C // // A program that demonstrates STL vectors and // vector iterators. // // It is a slightly modified version of D. Musser's // example. // // ------------------------------------------------ // STL items demonstrate: // Container class vector<> // vector<>::begin(), end(), operator[], operator==, // insert, erase // vector(vector<>) (copy constructor) // // Iterator classes // vector<>::iterator operator+=, operator-=, // operator*(void) (prefix *), // operator++(int) (postfix ++), // operator= // ostream_iterator<> // // Generic algorithms // copy, sort, binary_search, lower_bound, upper_bound #include #include #include void pause() { cin.get(); cout << endl; } main () { cout << "Create vector of 10 elements:\t"; vector v(10,0); ostream_iterator out(cout, " "); copy (v.begin(), v.end(), out); pause(); vector::iterator i = v.begin(); cout << "Modify 4th and 5th element:\t"; i += 4; *i++ = 7; // or v[4] = 7; *i = 9; // or v[5] = 9; copy (v.begin(), v.end(), out); pause(); vector::iterator where = find (v.begin(), v.end(), 9); cout << "Find 9, print starting from there:\t"; copy (where, v.end(), out); pause(); cout << "Insert 8 before 9:\t"; where = v.insert(where, 8); copy (v.begin(), v.end(), out); pause(); where += 3; cout << "Advance 3 positions, insert 4:\t"; where = v.insert(where, 4); copy (v.begin(), v.end(), out); pause(); cout << "Backup 6 positions, insert 11:\t"; where -= 6; where = v.insert (where, 11); copy (v.begin(), v.end(), out); pause(); cout << "Advance 2 positions, erase:\t"; v.erase (where+2); copy (v.begin(), v.end(), out); pause(); cout << "Sort the numbers:\t"; sort (v.begin(), v.end()); copy (v.begin(), v.end(), out); pause(); cout << "Search for 8:\t"; if (binary_search (v.begin(), v.end(), 8)) cout << "Yes, 8 occurs in vector v."; else cout << "No, didn't find 8 in vector v."; pause(); cout << "Search for 12:\t"; if (binary_search (v.begin(), v.end(), 12)) cout << "Yes, 12 occurs in vector v."; else cout << "No, didn't find 12 in vector v."; pause(); cout << "Find first instance of 8, and print starting from there:" << endl; where = lower_bound (v.begin(), v.end(), 8); copy (where, v.end(), out); pause(); cout << "Find first instance of 0, and print starting from there:" << endl; where = lower_bound (v.begin(), v.end(), 0); copy (where, v.end(), out); pause(); cout << "Find last instance of 0, and print starting from there:" << endl; where = upper_bound(v.begin(), v.end(), 0); copy (where, v.end(), out); pause(); vector w(v); cout << "Create a copy w=v:\t"; if (v == w) cout << "v and w have the same contents"; else cout << "v and w have different contents"; pause(); w[5] = 17; cout << "Change one element of w:\t"; if (v == w) cout << "v and w have the same contents"; else cout << "v and w have different contents"; cout << endl; }