c++ – Standard algorithms std::copy_backward and std::reverse_copy

Question:

Couldn't find an example when it's more convenient to use std::copy_backward instead of std::reverse_copy . And how does the existence of the second not make us forget about the first? Can you give an example (any)?

Answer:

These two functions do different things.

std::copy_backward does not change the order of elements in a range, but std::reverse_copy does. Also, one copies to the end of the target range and the other to the beginning.

For instance:

std::vector<int> mas1 = {1, 2, 3, 4, 5};
std::vector<int> mas2(8, 0);
std::vector<int> mas3(8, 0);
std::copy_backward(mas1.begin(), mas1.end(), mas2.end()); 
std::reverse_copy(mas1.begin(), mas1.end(), mas3.begin()); 
// mas2 = {0, 0, 0, 1, 2, 3, 4, 5}
// mas3 = {5, 4, 3, 2, 1, 0, 0, 0}
Scroll to Top