function template
<algorithm>

std::move_backward

template <class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 move_backward (BidirectionalIterator1 first,
                                        BidirectionalIterator1 last,
                                        BidirectionalIterator2 result);
Move range of elements backward
Moves the elements in the range [first,last) starting from the end into the range terminating at result.

The function returns an iterator to the first element in the destination range.

The resulting range has the elements in the exact same order as [first,last). To reverse their order, see reverse.

The function begins by moving *(last-1) into *(result-1), and then follows backward by the elements preceding these, until first is reached (and including it).

The ranges shall not overlap in such a way that result (which is the past-the-end element in the destination range) points to an element in the range (first,last]. For such cases, see move.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
template<class BidirectionalIterator1, class BidirectionalIterator2>
  BidirectionalIterator2 move_backward ( BidirectionalIterator1 first,
                                         BidirectionalIterator1 last,
                                         BidirectionalIterator2 result )
{
  while (last!=first) *(--result) = std::move(*(--last));
  return result;
}


Parameters

first, last
Bidirectional iterators to the initial and final positions in a sequence to be moved. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
result
Bidirectional iterator to the past-the-end position in the destination sequence.
This shall not point to any element in the range (first,last].

Return value

An iterator to the first element of the destination sequence where elements have been moved.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// move_backward example
#include <iostream>     // std::cout
#include <algorithm>    // std::move_backward
#include <string>       // std::string

int main () {
  std::string elems[10] = {"air","water","fire","earth"};

  // insert new element at the beginning:
  std::move_backward (elems,elems+4,elems+5);
  elems[0]="ether";

  std::cout << "elems contains:";
  for (int i=0; i<10; ++i)
    std::cout << " [" << elems[i] << "]";
  std::cout << '\n';

  return 0;
}


Output:
elems contains: [ether] [air] [water] [fire] [earth] [] [] [] [] []

Complexity

Linear in the distance between first and last: Performs a move-assignment for each element in the range.

Data races

The objects in both ranges are modified.

Exceptions

Throws if either an element move-assignment or an operation on iterators throws.
Note that invalid arguments cause undefined behavior.

See also