Lexicographically next permutation in C++

C++Server Side ProgrammingProgramming

Here we will see how to generate lexicographically next permutation of a string in C++. The lexicographically next permutation is basically the greater permutation. For example, the next of “ACB” will be “BAC”. In some cases, the lexicographically next permutation is not present, like “BBB” or “DCBA” etc.

In C++ we can do it by using a library function called next_permutation(). This is present in the algorithm header file.


#include <iostream>
#include <algorithm>
using namespace std;
main() {
   string s = "DBAC";
   for(int i = 0; i<5; i++) {
      bool val = next_permutation(s.begin(), s.end());
      if (val == false) {
         cout << "No next permutation" << endl;
      } else
      cout << "Next: " << s << endl;


Next: DBCA
Next: DCAB
Next: DCBA
No next permutation
Published on 02-May-2019 08:32:16