Mani
Mani

Reputation: 1

Subsequence of a string without using extra array

void justPrintSubsequnce(string input, string output){
    if(input.length() == 0){
        cout<<output<<" ";
        return;
    }

    justPrintSubsequnce(input.substr(1),output);
    justPrintSubsequnce(input.substr(1),output[0]+input[0]);

}

I tried to write a function to print out the subsequences of a string (input) using recursion and got this error for output[0] + input[0]:

no suitable constructor exists to convert from "int" to "std::__1::basic_string<char, std::__1::char_traits, std::__1::allocator>"

Upvotes: 0

Views: 80

Answers (1)

selbie
selbie

Reputation: 104514

output[0]+input[0] is attempting to add two char's together and forms an integer expression.

Instead of this:

justPrintSubsequnce(input.substr(1),output[0]+input[0]);

This:

auto s = output.substr(0,1) + input.substr(0,1);
justPrintSubsequnce(input.substr(1), s);

You can inline the expression for "s" into the function call directly.

justPrintSubsequnce(input.substr(1), output.substr(0,1) + input.substr(0,1));

While we're here, if you declare your function like this:

void justPrintSubsequnce(const string& input, const string& output){

You'll avoid redundant copies of strings (hence, less memory) and enable the compiler to do more optimizations.

Upvotes: 0

Related Questions