< Previous | Contents | Next >

Using Vectors

The vector class defines one kind of container provided by the STL. It meets the general description of a dynamic arrayan array that can grow and shrink in size as needed. In addition, vector defines member functions to manipulate vector elements. This means that the vector has all of the functionality of the array plus more.

At this point, you may be thinking to yourself: Why learn to use these fancy new vectors when I can already use arrays? Well, vectors have certain advantages over arrays, including:

n Vectors can grow as needed while arrays cannot. This means that if you use a vector to store objects for enemies in a game, the vector will grow to accommodate the number of enemies that get created. If you use an array, you have to create one that can store some maximum number of enemies. And if, during play, you need more room in the array than you thought, youre out of luck.

n Vectors can be used with the STL algorithms while arrays cannot. This means that by using vectors you get complex functionality like searching and sorting, built-in. If you use arrays, you have to write your own code to achieve this same functionality.

Using Vectors 117


There are a few disadvantages to vectors when compared to arrays, including:

n Vectors require a bit of extra memory as overhead.

n There can be a performance cost when a vector grows in size.

n Vectors may not be available on some game console systems.

Overall, vectors (and the STL) can be a welcome tool in most any project.


 

Introducing the Hero’s Inventory 2.0 ProgramPreparing to Use VectorsDeclaring a VectorUsing the push_back() Member FunctionUsing the size() Member FunctionIndexing VectorsCalling Member Functions of an ElementUsing the pop_back() Member FunctionUsing the clear() Member FunctionUsing the empty() Member Function