prev_permutation() in C++

«
»
This C++ program demonstrates the prev_permutation algorithm. The string is first sorted in reverse manner by passing the reverse iterators to the sort function and then permuted using prev_permutation. The prev_permutation takes iterators to the beginning and end of the string to be permuted and overwrites the value of the string with its previous lexicographic permutation. The function returns true if prev_permutation is available otherwise returns false.

Here is the source code of the C++ program which demonstrates the prev_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 prev_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.rbegin(), s.rend());
  15.     std::cout << "Permutations of " << s << std::endl;
  16.     do
  17.     {
  18.         std::cout << s << "\t";
  19.     }
  20.     while (prev_permutation(s.begin(), s.end()));
  21.     return 0;
  22. }

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

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

Note: Join free Sanfoundry classes at Telegram or Youtube
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 & technical discussions at Telegram SanfoundryClasses.