CTEC1335/2008F ============== The Vector Template Class ------------------------- Use the Standard Template Library (STL). see http://www.cplusplus.com/reference/stl/vector/ #include using namespace std ; New types: vector vector vector vector A vector is an array whose memory is managed automatically, and which has a variable (practically unlimited size). Member functions: ---------------- .push_back( ) Add a new element onto the end of a vector. .size( ) Get the number of elements in the vector. .at( ) Get the element at a certain index (which must be in the range 0 to .size( ) - 1 [like an array].) operator[ ] Access a vector like you would an array. The index has the same restrictions as for arrays and the at( ) member function. Iterators: --------- These are used to traverse through the entire collection of elements, without having to know the number of elements and without using an array index. vector<_>::iterator Type for forward direction iterator. Member functions to use in a for loop: .begin( ) .end( ) vector<_>::reverse_iterator Type for reverse direction iterator. Member functions to use in a for loop: .rbegin( ) .rend( ) Iterator Example ---------------- #include #include #include using namespace std ; int main( ) { vector list ; string line ; cout << "Enter a list of words, one word per line." << endl << "Press Enter twice when you are done." << endl ; while ( ! getline( cin, line ).eof( ) ) { if ( line.length( ) == 0 ) { break ; } list.push_back( line ) ; } cout << endl << "The list of words you entered:" << endl << endl ; vector::iterator it ; for ( it = list.begin( ) ; it < list.end( ) ; it++ ) { cout << *it << endl ; } cout << endl << "The list of words you entered in reverse:" << endl << endl ; vector::reverse_iterator rit ; for ( rit = list.rbegin( ) ; rit < list.rend( ) ; rit++ ) { cout << *rit << endl ; } }