blob: a1c1bcd3609ac4089b26f44c2eeffe1374231dbb [file] [log] [blame]
 reverse()
Apache C++ Standard Library Reference Guide

reverse()

Library:  Algorithms

Function

Local Index

No Entries

Summary

An algorithm that reverses the order of elements in a sequence

Synopsis

#include <algorithm>

namespace std {
template <class BidirectionalIterator>
void reverse(BidirectionalIterator start,
BidirectionalIterator finish);
}

Description

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.

Complexity

reverse() performs exactly (finish - start)/2 swaps.

Example

//
//  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