
Module: Standard C++ Library Library: Algorithms
Function
An algorithm that reverses the order of elements in a sequence
#include <algorithm>
namespace std {
template <class BidirectionalIterator>
void reverse(BidirectionalIterator start,
BidirectionalIterator finish);
}
The algorithm reverse() reverses the elements in a sequence so that the last element becomes the new first element, and the first element becomes the new last. For each non-negative integer i <= (finish - start)/2, reverse() applies iter_swap() to all pairs of iterators start + I, (finish - I) - 1.
reverse() performs exactly (finish - start)/2 swaps.
//
// 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).