Generate All Permutations of a String in C++

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 the std::sort and std::next_permutation functions.
  • #include <string>: This header file is included to use the std::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 uses std::next_permutation to generate each permutation. The function std::next_permutation rearranges the elements to the next lexicographical permutation and returns false 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 with inputString as the argument to print all permutations of the entered string.

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 the std::next_permutation function.
  • Function main: Handles user input and invokes the printPermutations function to display permutations.

Leave a Reply

Your email address will not be published. Required fields are marked *