
Module: Standard C++ Library Library: Algorithms
Function
An algorithm that reverses the order of elements in a sequence while copying them to a new sequence
#include <algorithm>
namespace std {
template <class BidirectionalIterator, class OutputIterator>
OutputIterator reverse_copy(BidirectionalIterator start,
BidirectionalIterator finish,
OutputIterator result);
}
The reverse_copy() algorithm copies the range [start, finish) to the range [result, result + (finish - start)) such that for any nonnegative integer i < (finish - start), the following assignment takes place:
*(result + (finish - start) - i) = *(start + i)
reverse_copy() returns result + (finish - start). The ranges [start, finish) and [result, result + (finish - start)) must not overlap.
reverse_copy() performs exactly (finish - start) assignments.
//
// reverse.cpp
//
#include <algorithm> // for reverse, reverse_copy
#include <vector> // for vector
#include <iostream> // for cout, endl
#include <iterator> // for ostream_iterator
int main ()
{
typedef std::vector<int, std::allocator<int> > Vector;
typedef std::ostream_iterator<int, char,
std::char_traits<char> >
Iter;
// Initialize a vector with an array of integers.
const Vector::value_type a[] = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10 };
Vector v (a + 0, a + sizeof a / sizeof *a);
// Print out elements in original (sorted) order.
std::cout << "Elements before reverse: \n ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));
// Reverse the ordering.
std::reverse (v.begin (), v.end ());
// Print out the reversed elements.
std::cout << "\n\nElements after reverse: \n ";
std::copy (v.begin (), v.end (), Iter (std::cout, " "));
std::cout << "\n\nA reverse_copy to cout: \n ";
std::reverse_copy (v.begin (), v.end (),
Iter (std::cout, " "));
std::cout << std::endl;
return 0;
}
Program Output:
Elements before reverse:
1 2 3 4 5 6 7 8 9 10
Elements after reverse:
10 9 8 7 6 5 4 3 2 1
A reverse_copy to cout:
1 2 3 4 5 6 7 8 9 10
ISO/IEC 14882:1998 -- International Standard for Information Systems -- Programming Language C++, Section 25.2.9
Copyright (c) 1994-2006 Rogue Wave Software, a Quovadx Division.
Licensed under the Apache License, Version 2.0.
Contact Rogue Wave about documentation or support issues. You can also seek help from other developers through the Apache stdcxx community (see below).