std::copy_backward
Defined in header <algorithm> | ||
|---|---|---|
template< class BidirIt1, class BidirIt2 > BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last ); | (constexpr since C++20) |
Copies the elements from the source range [first, last) to the destination range ending at d_last, starting from last and proceeding to first (reverse order).
If d_last is in (first, last], the behavior is undefined.
Parameters
| first, last | - | the pair of iterators defining the source range |
| d_last | - | the past-the-end iterator of the destination range |
| Type requirements | ||
-BidirIt must meet the requirements of LegacyBidirectionalIterator. |
||
Return value
An iterator to the last copy-assigned element in the destination range, or d_last if no element is copied.
Complexity
Exactly std::distance(first, last) 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 <numeric>
#include <vector>
int main()
{
std::vector<int> source(4);
std::iota(source.begin(), source.end(), 1); // fills with 1, 2, 3, 4
std::vector<int> destination(6);
std::copy_backward(source.begin(), source.end(), destination.end());
std::cout << "destination contains: ";
for (auto i: destination)
std::cout << i << ' ';
std::cout << '\n';
}
Output:
destination contains: 0 0 1 2 3 4
Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 1206 | C++98 | 1. the behavior was well-defined if d_last == last2. the behavior was undefined if d_last == first | 1. made undefined 2. made well-defined |
See also
|
(C++20) | copies a range of elements in backwards order (algorithm function object) |
|
(C++11) | copies a range of elements to a new location (function template & algorithm function object) |
|
(C++20)(C++20) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/cpp/algorithm/copy_backward