Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the line "subsets.push_back(n);" give me an error in the following code?

Tags:

c++

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'""

like image 614
Alok Raj Avatar asked Jan 20 '26 03:01

Alok Raj


1 Answers

As mentioned in comment:

[You code contains an] infinite loop. You are calling subsets.push_back inside loop, so subsets.size is 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...
}
like image 71
darune Avatar answered Jan 22 '26 17:01

darune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!