Search code examples
c++stlgeneric-programmingstd

Difference between copy_backward and reverse_copy?


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.


Solution

  • 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.