I want to print out the contents of a vector in C++, here is what I have:
#include
#include
#include
#include
How about for_each
+ lambda expression:
#include
#include
...
std::vector vec;
...
std::for_each(
vec.cbegin(),
vec.cend(),
[] (const char c) {std::cout << c << " ";}
);
...
Of course, a range-based for is the most elegant solution for this concrete task, but this one gives many other possibilities as well.
Explanation
The for_each
algorithm takes an input range and a callable object, calling this object on every element of the range. An input range is defined by two iterators. A callable object can be a function, a pointer to function, an object of a class which overloads () operator
or as in this case, a lambda expression. The parameter for this expression matches the type of the elements from vector.
The beauty of this implementation is the power you get from lambda expressions - you can use this approach for a lot more things than just printing the vector.