next_permutation


Change sequence to next lexicographic permutation.

Arrange the sequence [ first ... last ) into its next permutation and return true . If there is no next permutation, arrange the sequence into the first 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 next_permutation
  (
  BidirectionalIterator first,
  BidirectionalIterator last
  );

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

Complexity

Time complexity is linear. Space complexity is constant.

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

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

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

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

0 2 1
Example <ospace/osstd/examples/nextprm1.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 )
    {
    next_permutation( v1.begin(), v1.end() );

    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
Example <ospace/osstd/examples/nextprm2.cpp>
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
#include <vector>

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

  for ( int i = 0; i < 9; ++i )
    {
    next_permutation( v1.begin(), v1.end(), less< char >() );

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

ABC
ACB
BAC
BCA
CAB
CBA
ABC
ACB
BAC
BCA

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