// Demonstrating the vector constructors, accessors, iterators #include #include #include void print_vector (char *caption, const vector & V) { cout << caption << " : ["; for (int i=0; i < V.size(); i++) cout << " " << V[i] ; cout << "]" << endl; } int main() { cout << "Demonstrating Simple Use of vectors." << endl; int x[5] = {2, 3, 5, 7, 11}; // Initialize vector1 to x[0] through x[4]: vector vector1(&x[0], &x[5]); // No initial elements and no size specification vector vector2; // basic container operations cout << "Vector 1 size: " << vector1.size() << endl << "Vector 2 size: " << vector2.size() << endl; cout << "Vector 1 capacity: " << vector1.capacity() << endl << "Vector 2 capacity: " << vector2.capacity() << endl; // You can use subscript to retrieve values (like regular array) cout << "Value of 4th element in Vector1: " << vector1[3] << endl; // populating the vector using "push_back" vector2.push_back(89); vector2.push_back(99); vector2.push_back(79); vector2.push_back(69); vector2.push_back(59); vector2.push_back(49); cout << "Vector 2 size: " << vector2.size() << endl << "Vector 2 capacity: " << vector2.capacity() << endl; // retrieving values using subscripts again cout << "Value of 1st element of vector2: " << vector2[0] << endl << "Value of 6th element of vector2: " << vector2[5] << endl; // using other vector constructors... // vector of size 5 vector vector3(5); cout << "Vector 3 size: " << vector3.size() << endl << "Vector 3 capacity: " << vector3.capacity() << endl; cout << "Value at vector3 position 4: " << vector3[3] << endl; // vector of size 5, initial value of each element 20 vector vector4(5, 20); cout << "Vector 4 size: " << vector4.size() << endl << "Vector 4 capacity: " << vector4.capacity() << endl; print_vector("vector1", vector1); print_vector("vector2", vector2); print_vector("vector3", vector3); print_vector("vector4", vector4); // iterator can also be used with vectors!! cout << "Vector 4 contents using iterators: [" ; for (vector::iterator vp = vector4.begin(); vp != vector4.end(); vp++) cout << " " << *vp; cout << " ] " << endl ; }