Bad Alloc Error C++ in Ferris Wheel cses problem

  alloc, c++

I’ve been working on the Ferris Wheel cses Problem and I’ve runned to an issue with my code. When my code is executed an error pops up that says "terminate called after throwing an instance of ‘std::bad_alloc’ ". I cant find a problem with my code. Also my code is similar with other solutions that i have found.

#include<bits/stdc++.h>
#include <vector>
using namespace std;
typedef long long ll;
int main()
{
    freopen("ferriswheel.in", "r", stdin);
    ll n, x, p, total = 0;
    vector<ll> weight(n);
    cin >> n >> x;
    for(int i = 0; i < n; i++)
    {
        cin >> p;
        weight[i] = p;
    }
    sort(weight.begin(),weight.end());
    int i = 0;
    int j = n - 1;
    while(i >= j)
    {
        if(weight[i] + weight[j] <= x)
        {
            i++;
            j--;
            total++;
        }
        else 
        {
           j--;
        }
     }
     cout << total << endl;
}

Thanks for your assistance.

Source: Windows Questions C++

LEAVE A COMMENT