tags:

views:

117

answers:

1
#include <iostream>
#include <string.h> // for strlen
#include <stdlib.h> // for atoi
#include <sstream>
void expand_combinations(const char *remaining_string, std::ostringstream& i, int remain_depth)
{
    if(remain_depth==0)
    {
        std::cout << i.str() << std::endl;
        return;
    }

    for(int k=0; k < strlen(remaining_string); ++k)
    {
        std::ostringstream l;
        l << i.str();
        l << remaining_string[k];
        expand_combinations(remaining_string+k+1, l, remain_depth - 1);
    }
    return;
}
int main(int argc, char **argv)
{
    std::ostringstream i;
    if(argc<3) return 1;
    expand_combinations(argv[1], i, atoi(argv[2]));
    return 0;
}

How can this code be changed so that it doesn't use ostringstream?

+2  A: 

The following is your code with string in place of ostringstream. Normally I'd refactor the code but since your question was pretty specific I'll leave it alone.

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

void expand_combinations(const char *remaining_string, string const & s, int remain_depth)
{
    if(remain_depth==0)
    {
        std::cout << s << std::endl;
        return;
    }

    for(int k=0; k < strlen(remaining_string); ++k)
    {
        string str(s);
        str.append(1, remaining_string[k]);
        expand_combinations(remaining_string+k+1, str, remain_depth - 1);
    }
    return;
}

int main(int argc, char **argv)
{
    if(argc<3) return 1;
    expand_combinations(argv[1], "", atoi(argv[2]));
    return 0;
}
Paul
What exactly do you mean by refactor the code? Do you already see something that can be optimized?
awakeFromNib