Home » C++ algorithm next_permutation() function

C++ algorithm next_permutation() function

by Online Tutorials Library

C++ Algorithm next_permutation ()

C++ Algorithm next_permutation() function is used to reorder the elements in the range [first, last) into the next lexicographically greater permutation.

A permutation is specified as each of several possible ways in which a set or number of things can be ordered or arranged. It is denoted as N! where N = number of elements in the range.

Elements are compared using operator < for the first version or using the given binary comparison function comp for the second version.

Syntax

Parameter

first: A bidirectional iterator pointing to the first element in the range to be permuted.

last: An input iterator pointing the position one past the last in the range to be permuted.

comp: A user-defined binary predicate function that accepts two arguments and returns true if the two arguments are in order, otherwise returns false. It follows the strict weak ordering to order the elements.

Return value

It returns true if the function could reorder the object as a lexicographically greater permutations.

Else, the function returns false to indicate that the arrangement is not greater than the previous, but the lowest possible (sorted in ascending order).

Complexity

Complexity is up to linear in half the distance between first and last.

Data Races

The objects in the range [first, last) are modified.

Exceptions

This function throws an exception if either element are swapped or an operation on iterator throws an exception.

Note: The invalid parameters cause an undefined behavior.

Example 1

Let’s see the simple example to demonstrate the use of next_permutation():

Output:

aab  aba   baa  

Example 2

Let’s see another simple example:

Output:

The 3! possible permutations with 3 elements:  1 2 3  1 3 2  2 1 3  2 3 1  3 1 2  3 2 1  After loop: 1 2 3  

Example 3

Let’s see another simple example:

Output:

1 2 3 4   1 2 4 3   1 3 2 4   1 3 4 2   1 4 2 3   1 4 3 2   2 1 3 4   2 1 4 3   2 3 1 4   2 3 4 1   2 4 1 3   2 4 3 1   3 1 2 4   3 1 4 2   3 2 1 4   3 2 4 1   3 4 1 2   3 4 2 1   4 1 2 3   4 1 3 2   4 2 1 3   4 2 3 1   4 3 1 2   4 3 2 1   

Example 4

Let’s see a simple example:

Output:

231 312 321  

Next TopicC++ Algorithm

You may also like