0
#include <iostream>
#include <vector>
using namespace std;
int count;
vector<char*> ans;
char result[1000];   //result will store the current subsequence
void printAllSubsequences(char str[], int beg, int res_index) {
    if(str[beg] == '\0') {  // if you reach end of string, print the result(i.e.,one of the subsequences). Recursion quits after encountering the last element in the given string str
        result[res_index] = '\0';
        ++count;
        cout<<result<<' ';
        ans.push_back(result);
        return;
    }

    printAllSubsequences(str, beg+1, res_index);
    result[res_index] = str[beg];
    printAllSubsequences(str, beg+1, res_index+1);
}
int main() {
    char str[1000];   //str is the string whose permutations we have to find
    cin >> str;
    char result[1000];
    printAllSubsequences(str, 0, 0);
    cout<<count<<endl;
    for(vector<char*>::iterator ii = ans.begin(); ii!=ans.end(); ++ii){
        cout<<(*ii)<<' ';
    }
    cout<<endl;
}

When I give an input as

abcd

I get the following as output

 d c cd b bd bc bcd a ad ac acd ab abd abc abcd 16
 abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd

So, the first line returns the subsequences; great! For, the second if I store the same in a vector and then try to print it out, it gives me the same string over and over again. Where could the implementation be possibly going wrong ?

Thanks.

9
  • 1
    What are you expecting as result? Commented Jul 7, 2017 at 19:11
  • Use std::string instead of char arrays. Commented Jul 7, 2017 at 19:11
  • You know that you are not working on copies of the arrays? Commented Jul 7, 2017 at 19:14
  • 1
    Show a sample input and the expected output Commented Jul 7, 2017 at 19:17
  • 1
    @Aryan vector<char*> ans; -- One of the worst code smells in C++. Unless you have a compelling reason (yes there are reasons, but not anything for what you're trying to achieve) , use vector<std::string>.. Commented Jul 7, 2017 at 19:23

1 Answer 1

2

Where could the implementation be possibly going wrong?

Here:

vector<char*> ans;

Explanation: You have created a vector of a pointer. Since every time you push the same pointer in the array so once the pointed memory output gets changed it will change the output of already pushed entries as well.

To fix the issue use std::string instead of char array

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.