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.
/*
* C++ Program to demonstrate the prev_permutation() algorithm
*/
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string s;
std::cout << "Enter the string : ";
std::cin >> s;
sort(s.rbegin(), s.rend());
std::cout << "Permutations of " << s << std::endl;
do
{
std::cout << s << "\t";
}
while (prev_permutation(s.begin(), s.end()));
return 0;
}
$ 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.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Next Steps:
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Buy C++ Books
- Buy Computer Science Books
- Apply for Information Technology Internship
- Practice Computer Science MCQs
- Buy Programming Books