Game Development Reference
In-Depth Information
Chapter
14
STL Array and Vector
You saw in Chapter 13 that the STL provides different types of
string
classes by specializing a
template to create different implementations. This is where the template part of the STL comes from.
The STL
string
classes are what we call
containers
, because they store string data. In this chapter
you will see two more of the STL's containers in the
array
and
vector
templates.
STL's
array
class can be used in place of the built-in array types that you have seen earlier in
this topic. This allows you to use arrays in the same way you would use other STL containers; for
example, the STL
array
template provides
iterator
access to the array elements. The size of an
STL array is still determined at compile time. Sometimes you might not know how many elements
you will need to store in your collection, and this is where the
vector
template is useful. A
vector
stores any number of elements and can dynamically grow and shrink to accommodate more or less
items at runtime. Let's take a look at how these templates can be used.
The STL Array Template
Before we get into STL arrays, it is worth remembering how to define a traditional C-style array in
C++, as shown in Listing 14-1.
Listing 14-1. A Traditional C-Style
Array
const unsigned int ARRAY_SIZE = 5;
int oldArray[ARRAY_SIZE] = { 0, 1, 2, 3, 4 };
Hopefully you find that familiar. Listing 14-2 shows how you can construct an array holding the same
values using a C++ STL
array
container.
Listing 14-2. An STL
array
Container
const unsigned int ARRAY_SIZE = 5;
std::array<int, ARRAY_SIZE> newArray = { 0, 1, 2, 3, 4 };
157