I am reading C++ primer and saw these two functions that seem to have the same functionality. Could anyone help and tell me what is the difference between the two? Thanks.
C++ Algorithm reverse_copy() function is used to copy the elements from the range[first, last) to another range beginning at result in such a way that the elements in the range are in reverse order.
std::copy, std::copy_if. Copies the elements in the range, defined by [first, last) , to another range beginning at d_first . 1) Copies all elements in the range [first, last) starting from first and proceeding to last - 1. The behavior is undefined if d_first is within the range [first, last) .
copy() function is a library function of algorithm header, it is used to copy the elements of a container, it copies the elements of a container from given range to another container from a given beginning position. Note:To use copy() function – include <algorithm> header or you can simple use <bits/stdc++.
reverse_copy
actually puts the elements in reverse order.
1 2 3 4 5 - > 5 4 3 2 1
copy_backward
simply copies the elements backwards, but preserves their relative order.
1 2 3 4 5
5 is copied first, but put in the last spot. So your output is still:
1 2 3 4 5
http://en.cppreference.com/w/cpp/algorithm/copy_backward
Copies the elements from the range, defined by [first, last), to another range ending at d_last. The elements are copied in reverse order (the last element is copied first), but their relative order is preserved.
http://en.cppreference.com/w/cpp/algorithm/reverse_copy
Copies the elements from the range [first, last) to another range beginning at d_first in such a way that the elements in the new range are in reverse order.
std::copy_backwards
does:
Copies the elements from the range, defined by [first, last), to another range ending at d_last. The elements are copied in reverse order (the last element is copied first), but their relative order is preserved.
std::reverse_copy
Copies the elements from the range [first, last) to another range beginning at d_first in such a way that the elements in the new range are in reverse order.
So the difference is that std::copy_backwards
start copying at the end and works backwards, keeping original positioning, whereas std::reverse_copy
starts copying at the beginning going forward, but puts them in the reverse order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With