8

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.

Sean
  • 2,649
  • 3
  • 21
  • 27

2 Answers2

10

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.

Martin York
  • 257,169
  • 86
  • 333
  • 562
Rivasa
  • 6,510
  • 3
  • 35
  • 64
2

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.

Rivasa
  • 6,510
  • 3
  • 35
  • 64
NathanOliver
  • 171,901
  • 28
  • 288
  • 402