Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 799
Sean Avatar asked Dec 02 '15 17:12

Sean


People also ask

What does reverse_ copy do?

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.

How does STD copy work?

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

How does the copy function work C++?

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


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.

like image 76
Rivasa Avatar answered Nov 09 '22 17:11

Rivasa


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.

like image 21
NathanOliver Avatar answered Nov 09 '22 17:11

NathanOliver