next_permutation() in C++

This C++ program demonstrates the next_permutation algorithm. The program first sorts the string and then permutes the entire string. The next_permutation takes iterators to the beginning and end of the string to be permuted and overwrites the value of the string with next lexicographic permutation. The function returns true if next_permutation is available otherwise returns false.

Here is the source code of the C++ program which demonstrates the net_permutation algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to demonstrate the next_permutation() algorithm
  3.  */
  4. #include <iostream>
  5. #include <string>
  6. #include <algorithm>
  7.  
  8. int main()
  9. {
  10.     std::string s;
  11.  
  12.     std::cout << "Enter the string : ";
  13.     std::cin >> s;
  14.     sort(s.begin(), s.end());
  15.     std::cout << "Permutations of " << s << std::endl;
  16.     do
  17.     {
  18.         std::cout << s << "\t";
  19.     }
  20.     while (next_permutation(s.begin(), s.end()));
  21.     return 0;
  22. }

$ a.out
Enter the string : ABCD
Permutations of ABCD
ABCD    ABDC    ACBD    ACDB    ADBC    ADCB    BACD    BADC    BCAD
BCDA    BDAC    BDCA    CABD    CADB    CBAD    CBDA    CDAB    CDBA
DABC    DACB    DBAC    DBCA    DCAB    DCBA

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.