-4

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.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • 1
    A good code indentation is recommended. – youtao guo Sep 29 '22 at 09:44
  • 2
    I'd also recommend to read [Why should I not #include ?](https://stackoverflow.com/questions/31816095) and [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/questions/1452721). Using both is a good way to introduce strange errors. – Lukas-T Sep 29 '22 at 09:58
  • 2
    Whichever C++ textbook taught you to use `` -- you need to throw it away and get a different C++ textbook. If you copied that off some web site, without any explanation, don't visit that web site any more. If you saw this in some clown's Youtube video, unsubscribe from that channel, you're not learning proper C++. Most C++ compilers in the world don't have this header file, and will not compile the shown code. – Sam Varshavchik Sep 29 '22 at 11:08

3 Answers3

2

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.

youtao guo
  • 73
  • 1
  • 4
1

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

Nikhil
  • 275
  • 1
  • 9
0

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.

dani_l_n
  • 376
  • 1
  • 11