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::sort
andstd::next_permutation
functions.#include <string>
: This header file is included to use thestd::string
class.
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-while
loop usesstd::next_permutation
to generate each permutation. The functionstd::next_permutation
rearranges the elements to the next lexicographical permutation and returnsfalse
when all permutations have been generated.
3. Function: main
- Purpose: To drive the program by getting user input and calling the
printPermutations
function. - Implementation:
- The user is prompted to enter a string, which is stored in the variable
inputString
. - The
printPermutations
function is called withinputString
as 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_permutation
function. - Function
main
: Handles user input and invokes theprintPermutations
function to display permutations.