Home > OS >  differences between std::for_each and std::copy, std::ostream_iterator<T> when printing a vect
differences between std::for_each and std::copy, std::ostream_iterator<T> when printing a vect

Time:01-16

Recently, I have come across code that prints a vector like so

std::copy(vec.begin(), vec.end(), std::ostream_iterator<T>(std::cout, " ");

comparing that to what I am used to (for_each or range based for loop)

auto print = [](const auto & element){std::cout << element << " ";};
std::for_each(vec.begin(), vec.end(), print);
  1. Does the copy method create an additional copy? In for_each I can have a const reference.
  2. The documentation for copy states it copies elements from one range to another range. How is std::ostream_iterator<T> a range? And if it is then where does it begin and end?
  3. I need to templatize the copy method, while for_each I can just auto which seems more convenient.

This makes me feel like the for_each method is better?

CodePudding user response:

  1. No, the ostream_iterator uses the std::ostream& operator<<(std::ostream&, const T&); overload and will not create additional copies as can be seen in this demo.
  2. The ostream_iterator is a single-pass LegacyOutputIterator that writes successive objects of type T. The destination range can be seen as the Ts printed on std::cout.

This makes me feel like the for_each method is better?

std::for_each is a more generic algorithm. With std::copy you specify that you aim to copy from one range to another. Some would say that's easier to understand and therefore makes the code easier to maintain.

On the other hand, a plain range-based for loop is pretty easy to understand too:

for(auto& element : vec) std::cout << element << ' ';
  •  Tags:  
  • Related