Game Development Reference
In-Depth Information
As you can see, the syntax changes a bit when using an STL
array
. You can see the now familiar
template specialization syntax at work. The first template parameter tells the compiler that you
would like to use the
int
type for storing the values in our
array
. The second parameter then tells
the compiler how many elements we would like our array to hold. Now that you know how to create
arrays using the STL
array
template, I can show you some examples of why this is desirable over
using standard C-style arrays. Listing 14-3 shows several examples of different ways you can use to
find elements in an
array
.
Listing 14-3. Searching in an
array
using MyArray = std::array<int, ARRAY_SIZE>;
void FindInArray(MyArray myArray)
{
for (unsigned int i = 0; i < ARRAY_SIZE; ++i)
{
if (myArray[i] == 2)
{
cout << "Found: " << myArray[i]
<< " at position: " << i << endl;
}
}
for (auto iter=myArray.begin(); iter!=myArray.end(); ++iter)
{
if (*iter == 2)
{
cout << "Found: " << *iter << endl;
}
}
for (auto& number : myArray)
{
if (number == 2)
{
cout << "Found : " << number << endl;
}
}
MyArray::iterator found = find(myArray.begin(), myArray.end(), 2);
if (found != myArray.end())
{
cout << "Found : " << *found << endl;
}
}
The very first line in Listing 14-3 creates a
type alias
for our array type. You get a benefit when using
type aliases with template specializations in two ways. First it means that you do not have to type
out the full template specialization each time you wish to refer to that type. It also means that if you
need to change the type that you only have to change it in the type alias and it will apply to all of the
places where the type alias is used. The alias
MyArray
can now be used in place of
std::array<int,
ARRAY_SIZE>
everywhere in our code.