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);
- Does the
copymethod create an additional copy? Infor_eachI can have a const reference. - The documentation for
copystates it copies elements from one range to another range. How isstd::ostream_iterator<T>a range? And if it is then where does it begin and end? - I need to templatize the
copymethod, whilefor_eachI can justautowhich seems more convenient.
This makes me feel like the for_each method is better?
CodePudding user response:
- No, the
ostream_iteratoruses thestd::ostream& operator<<(std::ostream&, const T&);overload and will not create additional copies as can be seen in this demo. - The
ostream_iteratoris a single-pass LegacyOutputIterator that writes successive objects of typeT. The destination range can be seen as theTs printed onstd::cout.
This makes me feel like the
for_eachmethod 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 << ' ';
