Game Development Reference
In-Depth Information
The first
for
loop in Listing 14-3 shows the standard method for looping through
array
elements.
This syntax is the same whether looping over a C-style array or when using the STL
array
template.
The second loop uses iterators in the same manner as you saw when looping over the characters in
your strings in Chapter 13. You can then also see the range-based
for
loop used.
The last example is something a little different: It uses an STL
algorithm
to find the element we
would like in the
array
. You have already seen that the STL provides containers that you can use to
store elements and now you can see that the STL also provides algorithms that operate on those
containers. This algorithm is the
find
and it works by taking an iterator marking the beginning of
a range and an iterator marking the end of a range as well as the value we wish to search for. The
beginning and end iterators supplied to
find
do not have to be the beginning and end iterators
from your collection; they could have been the second and third iterators from our
array
. The
find
function returns an iterator to the first element that matches the supplied value. If no values match,
it returns the end iterator that you passed in. You can see this result tested in the
if
statement
following the
find
call.
The STL Vector Class
The STL
array
takes a size parameter that tells the compiler exactly how big we need the array to
be before our program ever runs. However, we might not always know how many elements we will
need. When this is the case, we can use the STL
vector
template. Listing 14-4 shows how you can
specialize
vector
.
Listing 14-4. Specializing STL
vector
using namespace std;
using MyVector = vector<int>;
MyVector myVector = { 0, 1, 2 };
myVector.push_back(3);
myVector.push_back(4);
Listing 14-4 shows that you can add new values to a vector even after it has been initialized. The
vector automatically resizes itself if it needs more memory to store the new element. You can
also insert elements into other places in a vector and erase elements. Listing 14-5 shows how this
is done.
Listing 14-5.
vector insert
and
erase
MyVector::const_iterator iter = myVector.cbegin() + 1;
myVector.insert(iter, 5);
myVector.erase(iter);
The
insert
and
erase
methods take a constant iterator to the position where we would like the insert
and remove operator to take place. The
insert
shown in Listing 14-5 would result in our vector
storing the values 0, 5, 1, 2, 3, 4 in that order, and the
erase
would remove from the same location,
which would remove the 5. It does not remove the 1, as the iterator points to the second location in
the vector, which is occupied by 5 after the
insert
. Each element after that location has moved one
position to the right.