I want to find the power set of a set of numbers and there is some issue I can't figure out with the code. What changes should I make??
vector<vector <int>> subsets={{}};
for(int i=0; i<a.size();i++){
int elem = a[i];
for(int j=0;j<subsets.size();j++){
vector<int> prev = subsets[j];
vector<int> n = prev;
n.push_back(elem);
subsets.push_back(n);
}
}
I am getting the following error : ""terminate called after throwing an instance of 'std::bad_alloc'""
As mentioned in comment:
[You code contains an] infinite loop. You are calling
subsets.push_backinside loop, sosubsets.sizeis increased at every iteration of loop and it cannot be stopped, until exception is called due to lack of memory.
Exception std::bad_alloc is thrown because the process is trying to allocate a too large memory block (as deemed by the OS) - there are ways around this but this is not the issue here, the issue is the infinite loop as already pointed out.
To avoid that particular issue you could use a range-based for loop instead (and avoid the push_back within the loop), such as:
for(vector<int> prev : subsets){
//do stuff...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With