简体   繁体   中英

differences between std::for_each and std::copy, std::ostream_iterator<T> when printing a vector

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?

  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 T s 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 << ' ';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM