next up previous contents
Next: Associative arrays/maps Up: Some basics of object-oriented Previous: Arrays of classes   Contents

The Standard Template Library (STL)

The above array usage is awkward because we need to know in advance how many nodes we will have. It is better to use vectors, as follows:


{}
#include <vector>
...
vector<Node*> nodes ;
...
// memory management missing
...
nodes[0]->set_id( 213 ) ;
xx = nodes[0]->x() ;
So the usage of this looks the same as before, but the memory management is still missing. An easy way to enter elements without having to worry about memory is to use one of the insertion operators:


{}
...
Node* node = new Node( ... );
nodes.push_back( node ) ; // add array element at end
...

It helps to use typedefs:


{}
...
typedef vector<Node*> Nodes ;
Nodes nodes ;
...
(instead of vector<Node*> nodes;).

Note that now


{}
Nodes nodes ;
essentially looks like and is used like


{}
Node* nodes[20] ;
except that the memory management is different.

vector<Node*> is template syntax; it means that we have a vector of type Node*. Instead of vector, you could think ``array''.

Besides vector, there are other pre-defined template classes, such as list and deque. They all have certain insertion and removal operations which do the memory management for us. In C++, this is known as the Standard Template Library (STL). It is included in all new enough C++ compilers.

We will always hide templates via typedefs so in general they will not really show up. They do however (unfortunately) make a big difference in compiler error messages (see 5.3).


next up previous contents
Next: Associative arrays/maps Up: Some basics of object-oriented Previous: Arrays of classes   Contents
2004-02-02