//---------------------------------------------------------------- // // vector.cpp // // Code to illustrate the use of vectors. // // written by: Simon Parsons // modified : 5th June 2010 // //---------------------------------------------------------------- #include #include // Remember we need this to use vectors using namespace std; //---------------------------------------------------------------- int main() { // Here we declare a vector that has 10 elements. // and we use an index to set the values. vector V(10); for ( int i=0; i<10; i++ ) { V[i] = i * 10; } // Now use an iterator to print the elements out. vector::iterator p; for ( p = V.begin(); p != V.end(); p++ ) { cout << *p << " "; } cout << endl; // Add an element to the vector, and print it again. V.push_back(10); for ( p = V.begin(); p != V.end(); p++ ) { cout << *p << " "; } cout << endl; // Now remove the last two elements: V.pop_back(); V.pop_back(); for ( p = V.begin(); p != V.end(); p++ ) { cout << *p << " "; } cout << endl; // Now remove all the elements, one by one: while(!V.empty()){ cout << "Size is " << V.size() << " "; cout << "First element is " << V.front() << " "; cout << "Last element is " << V.back() << endl; V.pop_back(); } // Set up V as it was originally, but using puSh_back for ( int i=0; i<10; i++ ) { V.push_back(i * 10); } for ( p = V.begin(); p != V.end(); p++ ) { cout << *p << " "; } cout << endl; // create a vector W that holds 10 copies of the integer 20: vector W(10, 20); for ( p = W.begin(); p != W.end(); p++ ) { cout << *p << " "; } cout << endl; // create a vector X that is a copy of V: vector X(V.begin(), V.end()); for ( p = X.begin(); p != X.end(); p++ ) { cout << *p << " "; } cout << endl; }