Generate All Permutations of a Given String in C++
Program Code
#include
#include
#include
// Function to print all permutations of the given string
void printPermutations(std::string str) {
// Sort the string to ensure permutations are generated in lexicographical order
std::sort(str.begin(), str.end());
// Print all permutations using next_permutation
do {
std::cout << str << std::endl;
} while (std::next_permutation(str.begin(), str.end()));
}
int main() {
std::string inputString;
// Get the input string from the user
std::cout << "Enter a string: "; std::cin >> inputString;
// Call the function to print permutations
printPermutations(inputString);
return 0;
}
Program Explanation
This C++ program generates and prints all permutations of a given string. Here is a breakdown of its structure:
1. Includes and Namespaces
#include <iostream>: This header file is included to allow input and output operations.#include <algorithm>: This header file is included for thestd::sortandstd::next_permutationfunctions.#include <string>: This header file is included to use thestd::stringclass.
2. Function: printPermutations
- Purpose: To generate and print all permutations of a given string.
- Parameters: A single parameter
std::string str, which is the string for which permutations are to be generated. - Implementation:
std::sort(str.begin(), str.end());sorts the string in lexicographical order to ensure that the permutations are generated in the correct order.- The
do-whileloop usesstd::next_permutationto generate each permutation. The functionstd::next_permutationrearranges the elements to the next lexicographical permutation and returnsfalsewhen all permutations have been generated.
3. Function: main
- Purpose: To drive the program by getting user input and calling the
printPermutationsfunction. - Implementation:
- The user is prompted to enter a string, which is stored in the variable
inputString. - The
printPermutationsfunction is called withinputStringas the argument to print all permutations of the entered string.
- The user is prompted to enter a string, which is stored in the variable
How to Compile and Run
- Save the code in a file named
permutations.cpp. - Compile the program using a C++ compiler (e.g.,
g++ permutations.cpp -o permutations). - Run the executable (e.g.,
./permutations).
Explanation:
- Includes and Namespaces: The program includes necessary headers and uses standard namespace features.
- Function
printPermutations: It generates and prints all permutations of the input string by first sorting the string and then using thestd::next_permutationfunction. - Function
main: Handles user input and invokes theprintPermutationsfunction to display permutations.
