I've been reading "Effective STL" by Scott Meyers and I've noticed quite a few examples in the book where he prints the contents of a container by using std::copy
to copy the elements to std::cout
. To me this just feels very difficult to read compared to the alternative of using a range based for
loop (perhaps I just need to get used to it?)
// Given the following
std::vector<int> values = { 1, 2, 3, 4, 5, 6, 7, 8 };
// Print using `std::copy`
std::copy(values.begin(), values.end(), std::ostream_iterator<int>(std::cout, ", "));
// Print using a loop
for (const auto value : values)
{
std::cout << value << ", ";
}
This post seems to suggest that there is no significant performance gain for using std::copy
:
Do some people really find the std::copy
approach more readable than the range based for
loop?
Maybe if I only want to print half of the values...
std::copy(values.begin(), values.begin() + values.size()/2, std::ostream_iterator<int>(std::cout, ", "));
...but even then I can just do this:
for (auto it = values.begin(); it != values.begin() + values.size()/2; ++it)
{
std::cout << *it << ", ";
}
So my question is why would anyone prefer the std::copy
approach? Are there any situations where you can prove that std::copy
is truly a better option (or the only option)?