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.
-
You should bookmark this site: http://en.cppreference.com/w/ for future use. – Anon Mail Dec 02 '15 at 17:49
2 Answers
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.

- 257,169
- 86
- 333
- 562

- 6,510
- 3
- 35
- 64
-
but whats the point of `std::copy_backward` if we can just `std::copy` ? – 0xB00B Feb 18 '23 at 11:16
-
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.
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.

- 6,510
- 3
- 35
- 64

- 171,901
- 28
- 288
- 402