A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://en.cppreference.com/w/cpp/language/../keyword/../language/../algorithm/copy_backward.html below:

std::copy_backward - cppreference.com

template< class BidirIt1, class BidirIt2 >
BidirIt2 copy_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );

(constexpr since C++20)

Copies the elements from the range [firstlast) 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 (firstlast]. std::copy must be used instead of std::copy_backward in that case.

[edit] Parameters first, last - the pair of iterators defining the source range of elements to copy from d_last - the end of the destination range Type requirements -BidirIt must meet the requirements of LegacyBidirectionalIterator. [edit] Return value

Iterator to the last element copied.

[edit] Complexity

Exactly std::distance(first, last) assignments.

[edit] 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).

[edit] 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;
}
[edit] 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
[edit] 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 == last
2. the behavior was undefined if d_last == first 1. made undefined
2. made well-defined [edit] See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4