devsda
devsda

Reputation: 4222

where i am wrong in given program?

Here is my program to find all the subsets of given set. To solve it, I used recursion. But when I compiled it in windows on codeblocks. It gives

This application has requested the Runtime to terminate it in a unusual way.

and in gcc compiler it didn't show any answer, no response.

#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> findAllSubset(char c, vector<string> v) {
    int size = v.size();
    if(size == 1) {
        v.push_back("");
        return v;
    }
    c = v[size-1][0];
    v.pop_back();
    v = findAllSubset(c, v);

    for(int i = 0; i < v.size(); i++) {
        string s= "";
        if(v[i].size() == 0){
            s += c;
            v.push_back(s);
        }
        else {
            s += v[i] + c;
            v.push_back( s );
        }
    }
    return v;
}

main() {
    vector<string> v, ans;
    char c = 65;
    v.push_back("a");
    v.push_back("b");
    //v.push_back("c");
    //v.push_back("d");
    ans = findAllSubset(c, v);
    return 0;
}

Upvotes: 1

Views: 215

Answers (3)

learning
learning

Reputation: 94

The for loop is an infinite loop, each time an element is push_back in the vector, vector size increases making the condition i < v.size() is always true.

Upvotes: 5

steffen
steffen

Reputation: 8958

You keep pushing strings to your vector while you loop through it. There is the infinite loop. It is generally a bad idea to alter a container while looping through it.

Upvotes: 2

karka91
karka91

Reputation: 733

There seems to be an infinite loop. The program compiles and runs normally but never exits

Upvotes: 1

Related Questions