std::copy_backward

From cppreference.com
< cpp‎ | algorithm
 
 
Algorithm library
Execution policies (C++17)
Non-modifying sequence operations
(C++11)(C++11)(C++11)
(C++17)
Modifying sequence operations
(C++11)
copy_backward
(C++11)
(C++20)(C++20)
Operations on uninitialized storage
Partitioning operations
Sorting operations
(C++11)
Binary search operations
Set operations (on sorted ranges)
Heap operations
(C++11)
Minimum/maximum operations
(C++11)
(C++17)
Permutations
Numeric operations
C library
 
Defined in header <algorithm>
template< class BidirIt1, class BidirIt2 >
BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );
(until C++20)
template< class BidirIt1, class BidirIt2 >
constexpr BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );
(since C++20)

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.

The behavior is undefined if d_last is within (first, last]. std::copy must be used instead of std::copy_backward in that case.

Parameters

first, last - the range of the elements to copy
d_last - end of the destination range..
Type requirements
-
BidirIt must meet the requirements of LegacyBidirectionalIterator.

Return value

iterator to the last element copied.

Complexity

Exactly last - first assignments.

Notes

When copying overlapping ranges, std::copy is appropriate when copying to the left (beginning of the destination range is outside the source range) while std::copy_backward is appropriate when copying to the right (end of the destination range is outside the source range).

Possible implementation

template< class BidirIt1, class BidirIt2 >
BidirIt2 copy_backward(BidirIt1 first, BidirIt1 last, BidirIt2 d_last)
{
    while (first != last) {
        *(--d_last) = *(--last);
    }
    return d_last;
}

Example

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> from_vector;
    for (int i = 0; i < 10; i++) {
        from_vector.push_back(i);
    }
 
    std::vector<int> to_vector(15);
 
    std::copy_backward(from_vector.begin(), from_vector.end(), to_vector.end());
 
    std::cout << "to_vector contains: ";
    for (auto i: to_vector) {
        std::cout << i << " ";
    }
 }

Output:

to_vector contains: 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9

See also

copies a range of elements to a new location
(function template)