C++ Algorithm Next Permutation Function

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

Example

default (1)    template <class BidirectionalIterator>

         bool next_permutation (BidirectionalIterator first, BidirectionalIterator last);

custom (2)    template <class BidirectionalIterator, class Compare>

                     bool next_permutation (BidirectionalIterator first, BidirectionalIterator last, 

                                                              Compare comp);

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:

Example

#include <algorithm>

#include <string>

#include <iostream>

using namespace std;

 

int main()

{

    string s = "aba";

    sort(s.begin(), s.end());

    do {

        cout << s << '\n';

    } while(next_permutation(s.begin(), s.end()));

    

    return 0;

}

Output:

Output

aab

aba 

baa

Example 2

Let's see another simple example:

Example

#include <iostream>     // std::cout

#include <algorithm>    // std::next_permutation, std::sort

using namespace std;

int main () {

  int myints[] = {1,2,3};

  sort (myints,myints+3);

  cout << "The 3! possible permutations with 3 elements:\n";

  do {

    cout << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  } while ( next_permutation(myints,myints+3) );

  cout << "After loop: " << myints[0] << ' ' << myints[1] << ' ' << myints[2] << '\n';

  return 0;

}

Output:

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:

Example

#include <vector>

#include <iostream>

#include <algorithm>

using namespace std;

template<typename It>

bool next_permutation(It begin, It end)

{

        if (begin == end)

                return false;

        It i = begin;

        ++i;

        if (i == end)

                return false;

        i = end;

        --i;

        while (true)

        {

                It j = i;

                --i;

                if (*i < *j)

                {

                        It k = end;

                        while (!(*i < *--k))

                                /* pass */;

                        iter_swap(i, k);

                        reverse(j, end);

                        return true;

                }

                if (i == begin)

                {

                        reverse(begin, end);

                        return false;

                }

        }

}

int main()

{

        vector<int> v = { 1, 2, 3, 4 };

        do

        {

                for (int i = 0; i < 4; i++)

                {

                        cout << v[i] << " ";

                }

                cout << endl;

        }

        while (::next_permutation(v.begin(), v.end()));

}

Output:

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:

Example

#include <iostream>

#include <algorithm>

using namespace std;

// Program to find all lexicographically next permutations

int main()

{

    string s = "231";

    

    // Optional: sort the string in natural order before calling

    // std::next_permutation inside a loop to print all permutations,

    // not just the ones that follows specified string lexicographically

    // std::sort(begin(s), end(s));

    // find all lexicographically next permutations using 

    // std::next_permutation

    while (1)

    {

        // print current permutation

        cout << s << " ";

        // find next permutation in lexicographic order

        if (!next_permutation(begin(s), end(s)))

            break;

    }

    return 0;

}

Output:

Output

231 312 321

Input Required

This code uses input(). Please provide values below: