The C++ standard library comes with a host of useful container classes. However, using these classes means becoming familiar with the language of templates. Simply iterating through a collection requires the use of some quite verbose syntax.
For example, suppose we have a vector
of integers:
std::vector<int> intArray;
In C++03, the contents of the vector can be enumerated as follows:
for (std::vector<int>::iterator it = intArray.begin(); it != intArray.end(); ++it)
{
std::cout << *it;
}
In C++11, this can be simplified by using range-based loop syntax:
for (auto x : intArray)
{
std::cout << x;
}
To get a reference to the container element, we can write:
for (auto& x : intArray) ...
or
for (const auto& x : intArray) ...
The new syntax is much more readable and also works with other containers such as list
and map
.