[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Iterators Up: More C++ Previous: Templates

The Standard Library

The Standard Library includes container classes: classes whose purpose is to contain other objects. There are classes for vectors, lists, etc. Each of these classes can contain any type of object (as long as the object can be copied safely - if it can't, use pointers to elements instead). You can, for example, use a vector<int> (meaning 'a vector of ints') in much the same way as you would use an ordinary C array, except that vector eliminates the chore of managing dynamic memory allocation by hand.

   vector<int> v(3);    // Declare a vector (of size 3 initially) of ints
   v[0] = 7;
   v[1] = v[0] + 3;
   v[2] = v[0] + v[1];  // v[0] == 7, v[1] == 10, v[2] == 17  
   v.push_back(13);     // add another element - the vector has to expand

Note the use of the push_back function - adding elements this way will make the container expand.

The Standard Library also includes about 70 algorithms that manipulate the data stored in containers - reverse, insert, unique, transform etc. Note that these operations act on the elements without explicit use of loops.

To use these features you need to include the corresponding header file. For example, #include <vector> is needed for vectors. CUED users can read the Standard C++ Library Class Reference. See the C++ and the STL document for examples.



 
next up previous contents
Next: Iterators Up: More C++ Previous: Templates
Tim Love
2001-07-05