prev_permutation


Change a sequence to its previous lexicographical permutation.

Arrange the sequence [ first ... last ) into its previous permutation and return true . If there is no previous permutation, arrange the sequence into the last permutation and return false . The first version orders the permutations using operator< , whereas the second version uses the binary function compare .

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class BidirectionalIterator >
bool prev_permutation
  (
  BidirectionalIterator first,
  BidirectionalIterator last
  );

template< class BidirectionalIterator, class Compare >
bool prev_permutation
  (
  BidirectionalIterator first,
  BidirectionalIterator last,
  Compare compare
  );
  

Complexity

Time complexity is linear. Space complexity is constant.

Example <ospace/osstd/examples/prevprm0.cpp>
#include <iostream>
#include <algorithm>

int v1[ 3 ] = { 0, 1, 2 };

void
main()
  {
  prev_permutation( v1, v1 + 3 );

  for ( int i = 0; i < 3; ++i )
    cout << v1[ i ] << ` `;
  cout << "\n";
  }

2 1 0
Example <ospace/osstd/examples/prevprm1.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

void
main()
  {
  vector< int > v1( 3 );
  for ( size_t j = 0; j < v1.size(); ++j )
    v1[ j ] = j;
  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";

  for ( int i = 0; i < 9; ++i )
    {
    prev_permutation( v1.begin(), v1.end() );

    copy( v1.begin(), v1.end(), iter );
    cout << "\n";
    }
  }

0 1 2
2 1 0
2 0 1
1 2 0
1 0 2
0 2 1
0 1 2
2 1 0
2 0 1
1 2 0
Example <ospace/osstd/examples/prevprm2.cpp>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>

void
main()
  {
  vector< int > v1( 3 );
  for ( size_t j = 0; j < v1.size(); ++j )
    v1[ j ] = j;
  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";

  for ( int i = 0; i < 9; ++i )
    {
    prev_permutation( v1.begin(), v1.end(), greater< int >() );

    copy( v1.begin(), v1.end(), iter );
    cout << "\n";
    }
  }

0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
0 1 2
0 2 1
1 0 2
1 2 0

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.