// File: vexample.cxx // Illustrate how to use some GENERIC ALGORITHMS on VECTORS #include #include #include #include using namespace std; const int MYSIZE = 8; int main( ) { int i; // For an index :) int a[MYSIZE] = {5, 0, 6, 6, 4, 3, 9, 7}; // What is a VECTOR? // A container class that acts similar to an array vector v, w; vector::iterator p; // How do you put elements into a vector. One way is the push_back member function for (i = 0; i < MYSIZE; ++i) v.push_back(a[i]); // How do you access all the elements of a vector? // One way is through an iterator. for (p = v.begin( ); p != v.end( ); ++p) cout << *p << endl; // A second way is to treat the vector as if it were an array. for (i = 0; i < v.size( ); ++i) cout << v[i] << endl; // How do you insert something from the middle of a vector? // One way is the insert member function--which has several versions p = v.begin( ) + 2; // p is referring to v[2] v.insert(p, 42); // inserts 42 at location v[2], and everything else shifts over //--------------------------------------------------------------------- // How do you sort a vector? One way is the generic sort algorithm. sort(v.begin( ), v.end( )); // This sorts all of the vector, from small to big // WOO HOO! All of the generic algorithms also work with pointers that // point into an array (instead of iterators). sort(a, a + MYSIZE); // Copy mania! w.resize(v.size( )); copy(v.begin( ), v.end( ), w.begin( )); cout << "size " << w.size( ) << endl; for (i = 0; i < w.size( ); ++i) cout << w[i] << endl; cout << "size " << v.size( ) << endl; for (i = 0; i < v.size( ); ++i) cout << v[i] << endl; copy(a, a + 4, v.begin( )); cout << "size " << v.size( ) << endl; for (i = 0; i < v.size( ); ++i) cout << v[i] << endl; // How do insert a new number into a vector that's already sorted // in a way that keeps the whole things sorted? p = lower_bound(v.begin( ), v.end( ), 50); cout << ((p == v.end( )) ? "END" : "NOT END") << endl; v.insert(p, 50); cout << "size " << v.size( ) << endl; for (i = 0; i < v.size( ); ++i) cout << v[i] << endl; do { for (i = 0; i < v.size( ); ++i) cout << v[i] << ' '; cout << endl; delay(2000); } while (next_permutation(v.begin( ), v.end( ))); return 0; }