Search code examples
c++bad-alloc

C++ vector std::bad_alloc error in a program


I was trying to sort a vector having user defined data type having two values, on the basis of one. But i get the error of bad_alloc. this is the code :

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct s{
int value;
int weight;
};

bool comp(s a , s b){
return a.value>b.value;
}

int main(){
vector <s> p;
s temp;
int n;
cin>>n;
while(n>=1){
    cin>>temp.value;
    cin>>temp.weight;
    p.push_back(temp);
}
sort(p.begin(), p.end(), comp);
vector <s> :: iterator it;
for(it = p.begin(); it != p.end();it++){
    *it = temp;
    cout<<temp.value<<endl;
}

}

on running :

terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

can anyone help?


Solution

  • Problems that I see:

    Infinite loop

    In the loop

    while ( n >= 1)
    {
       ...
    }
    

    you are not changing the value of n. If n is greater 1 than at start of the loop, the loop will never end.

    Not checking the status of input

    You have

     cin >> temp.value;
     cin >> temp.weight;
    

    You are not checking whether those calls succeeded. You are assuming that they did and proceeding to use temp.

    Wrong way assignment

    In the final loop, you are using

    *it = temp;
    

    That will change the vector, not extract the value from the vector.


    Here's an updated version of main that should work.

    int main()
    {
       vector <s> p;
       s temp;
       int n;
       cin>>n;
       while(n>=1)
       {
          // If there is a problem reading, break.
          if ( !(cin>>temp.value) )
          {
             break;
          }
    
          // If there is a problem reading, break.
          if ( !(cin>>temp.weight) )
          {
             break;
          }
    
          p.push_back(temp);
    
          // Decrement n
          --n;
       }
    
       sort(p.begin(), p.end(), comp);
       vector <s> :: iterator it;
       for(it = p.begin(); it != p.end();it++)
       {
          // Extract the value from the vector and print it.
          temp = *it;
          cout<<temp.value<<endl;
       }
    }