Namespaces
Variants
Views
Actions

std::move_backward

From cppreference.com
< cpp‎ | algorithm
Revision as of 13:00, 10 February 2013 by Nate (Talk | contribs)

 
 
 

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <algorithm>
</td>

<td></td> <td></td> <tr class="t-dcl ">

<td >
template< class BidirIt1, class BidirIt2 >
BidirIt2 move_backward( BidirIt1 first, BidirIt1 last, BidirIt2 d_last );
</td>

<td class="t-dcl-nopad"> </td> <td > (since C++11) </td> </tr> Template:ddcl list end

Moves the elements from the range [first, last), to another range ending at d_last. The elements are moved in reverse order (the last element is moved first), but their relative order is preserved.

Contents

Parameters

first, last - the range of the elements to move
d_last - end of the destination range. If d_last is within [first, last), std::move must be used instead of std::move_backward.
Type requirements
-
BidirIt1, BidirIt2 must meet the requirements of BidirectionalIterator.

Return value

Iterator in the destination range, pointing at the last element moved.

Complexity

Exactly last - first move assignments.

Possible implementation

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

Example

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
 
int main()
{
    std::vector<std::string> src = {"foo", "bar", "baz"};
    std::vector<std::string> dest(src.size());
 
    std::cout << "src: ";
    for (const auto &s : src) {
        std::cout << s << ' ';
    }   
    std::cout << "\ndest: ";
    for (const auto &s : dest) {
        std::cout << s << ' ';
    }   
    std::cout << '\n';
 
    std::move_backward(src.begin(), src.end(), dest.end());
 
    std::cout << "src: ";                                                       
    for (const auto &s : src) {
        std::cout << s << ' ';
    }   
    std::cout << "\ndest: ";
    for (const auto &s : dest) {
        std::cout << s << ' ';
    }   
    std::cout << '\n';
}

Output:

src: foo bar baz 
dest:    
src:    
dest: foo bar baz

See also

Template:cpp/algorithm/dcl list move