Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
permutation
communitycreator

What is the next_permutation() function in C++?

Harsh Jain

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The next_permutation() function is available under the <algorithm.h> header file in C++.

This function rearranges the elements into the next lexicographicala generalization of the alphabetical order of the dictionaries greater permutationpossible ways in which a number of things can be reordered or arranged.

For example, if you have the elements [1, 2, 3], the next greater lexicographical permutation will be [1, 3, 2].

Lexicographic permutation using next_permutation()

Parameters

The next_permutation() accepts the following parameters:

  • first: This is the start position of your search space. It is an iterator that usually points to the start of an array.

  • last: This is the end position of your search space. It is an iterator that usually points to the last position of an array.

  • comp: This is an optional parameter that specifies the custom condition to swap the elements and create the next permutation.

Return type

The next_permutation() function returns true when it rearranges the elements in the next greater lexicographical permutation.

It swaps the elements in place. That means it will create the next permutation and store it back in the same array.

This way, you will lose your original array but you will not use up extra space.

Code

Let’s see the code now.

#include <iostream>
#include <algorithm>
using namespace std;
int main () {
int myints[] = {1,2,3};
next_permutation(myints, myints + 3);
for(int x: myints)
cout << x << " ";
return 0;
}
Use next_permutation() function in C++

Explanation

  • In line 6, we create an array of integers.

  • In line 8, we call the next_permutation() function.

  • Finally, in line 11, we print the next greater permutation.

This way, you can also run a loop to find all the permutations and check whether the next_permutation() function returns true or not.

RELATED TAGS

c++
permutation
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring