Permutes the order of the elements

View versions (1)

Definition

The next_permutation() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include <algorithm>
template < class BidirectionalIterator >
   bool next_permutation(
      BidirectionalIterator first, 
      BidirectionalIterator last
   );
template < class BidirectionalIterator, class BinaryPredicate >
   bool next_permutation(
      BidirectionalIterator first, 
      BidirectionalIterator last,
      BinaryPredicate comp
   );

Parameters:

ParameterDescription
firstA bidirectional iterator pointing to the position of the first element in the range to be permuted
lastA bidirectional iterator pointing to the position one past the final element in the range to be permuted
compUser-defined predicate function object that defines the comparison criterion to be satisfied by successive elements in the ordering. A binary predicate takes two arguments and returns true when satisfied and false when not satisfied

Description

Next_permutation function reorders the range [first, last) into the next permutation from the set of all permutations that are lexicographically ordered.

The first version uses operator< for comparison and the second uses the function object comp.

Return Value

Returns true if there was a next permutation and has replaced the original ordering of the range,false otherwise.

Complexity

The complexity is linear; performs at most (last - first) / 2 swaps.

References

Example 1
Problem

The following example of code prints all three permutations of the string "aba" using next_permutation function.

Workings
#include <algorithm>
#include <string>
#include <iostream>
int main()
{
    std::string s = "aba";
    std::sort(s.begin(), s.end());
    do {
        std::cout << s << '\n';
    } while(std::next_permutation(s.begin(), s.end()));

  return 0;
}
Solution

Output:

aab
aba
baa

See Also