copy_backward
Copies a range starting with the last element
Definition
The copy_backward() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.
Interface
#include <algorithm>
template < class BidirectionalIterator1, class BidirectionalIterator2 >
BidirectionalIterator2 copy_backward(
BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result
);Parameters:
| Parameter | Description |
| first | A bidirectional iterator addressing the position of the first element in the source range |
| last | A bidirectional iterator addressing the position that is one past the final element in the source range |
| result | A bidirectional iterator addressing the position of the one past the final element in the destination range |
Description
Copy_backwards is the same as http://www.codecogs.com/reference/computing/stl/algorithms/modifying/copy.php"copy", but the copy is made from the end of the source sequence to its beginning.
Return Value
Returns an iterator on the element following the last copied element, result - (last - first).
Complexity
The complexity is linear, there are last - first assignments.
References
Example 1
The following example demonstrates the difference between copy() and copy_backward().
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
// initialize source collection with ".......... abcdef.........."
vector<char> source(10,'.');
for (int c='a'; c<='f'; C++)
source.push_back(c);
source.insert(source.end(),10,'.');
PRINT_ELEMENTS(source,"source: ");
//copy all letters three elements in front of the 'a'
vector<char> c1(source.begin(),source.end());
copy (c1.begin()+10, c1.begin()+16, //source range
c1.begin()+7); //destination range
PRINT_ELEMENTS(c1,"c1: ");
//copy all letters three elements behind the 'f'
vector<char> c2(source.begin(),source.end());
copy_backward (c2.begin()+10, c2.begin()+16, //source range
c2.begin()+19); //destination range
PRINT_ELEMENTS(c2,"c2: ");
return 0;
}Output:
source: . . . . . . . . . . a b c d e f . . . . . . . . . .
c1: . . . . . . . a b c d e f d e f . . . . . . . . . .
c2: . . . . . . . . . . a b c a b c d e f . . . . . . .
- Nicolai M. Josuttis: "The C++ Standard Library"