Game Development Reference
In-Depth Information
Listing 14-7. std::sort
bool Descending(int first, int second)
{
return first > second;
}
void SortVector()
{
MyVector myVector = { 0, 1, 2, 3, 4 };
sort(myVector.begin(), myVector.end(), Descending);
for (auto& value : myVector)
{
cout << value << endl;
}
sort(myVector.begin(), myVector.end());
for (auto& value : myVector)
{
cout << value << endl;
}
}
The first call to
sort
reverses the order of our
vector
. This is achieved by the
Descending
function.
If this supplied function returns true, the elements are left in the current order; if it returns false,
the elements are switched. A practical example would be the elements 0 and 1. When these two
numbers are compared, 0 > 1 is false; therefore the elements would be switched to 1, 0, which is
what we want.
The second
sort
call does not take a comparison function as a parameter, so by default this would
use the comparison first < second.
Summary
The fact that the code in Listings 14-3 and 14-6 is identical other than for the types passed into
the function is a perfect example of the flexibility of the STL. The STL containers are written to be
interchangeable and the correct container should be used for the correct purpose.
You have seen in this chapter that you can replace your use of C-style arrays with STL
array
with
no impacts on any of the code you are writing. You can still use the
[]
operator to access values.
However, the STL implementation of
array
also allows you to use the powerful iterators and
algorithms that it supplies to coexist with the container classes.
The
array
should be used any time you have a collection of values to store and you know the exact
number you will need at compile time. If you need a collection that can grow or shrink as your
program runs, you should use the
vector
.