Home > Mobile >  Here it is the program of the printing all the permutation of the string all storing it in the vecto
Here it is the program of the printing all the permutation of the string all storing it in the vecto

Time:09-29

Here i want to store the all the permutation of the string in the vector but its only printing

#include <bits/stdc  .h>
using namespace std;

vector<string> str;

void swap(char* x, char* y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
void permute(char* a, int l, int r)
{
    int i;
    if (l == r) {
        cout << a << endl;
        str.push_back(a);
    }

    else {
        for (i = l; i <= r; i  ) {
            swap((a   l), (a   i));
            permute(a, l   1, r);
            swap((a   l), (a   i)); //backtrack
        }
    }
}
/* Driver program to test above functions */
int main()
{
    char str[] = "ABC";
    int n = strlen(str);
    int l = n;
    permute(str, 0, n - 1);
    for (int i = 0; i < 6; i  ) {
        cout << str[i] << endl;
    }
    return 0;
}

Here in the line no 16 i am storing the string in the vector and in the line 35 and 36 i am trying to print all the permutation again using the loop but its not working while rest of the code is the working the fine .So help me if i made any mistake.

CodePudding user response:

You defined a vector<string> named str in global. Then you defined a char str[] named str as well in main function. So in the scope of main, invoking str corresponds to the char str[] but vector<string>. Just try to use different variable names.

CodePudding user response:

Because you are accessing char str[], instead of vector str. Avoid using same name for global and local variables.

CodePudding user response:

A Global variable is, as it might sound, a variable that is Global to the code. That means, you can access it from every scope within the code.

Noticing your code, you have been repeating the variable 'str' both in main and as global.

Conclusion: you should change one of the variable's name.

  • Related