How to fix C++ error: terminate called after throwing an instance of 'std::bad_alloc'. what(): std::bad_alloc

How to fix C++ error: terminate called after throwing an instance of 'std::bad_alloc'. what(): std::bad_alloc

抱歉,我知道这类问题在这里已经有了答案,但我不知道如何将它用于我的代码。 我为一个接受数组并尝试最大化 |Ax−Ay|+|Ay−Az|+|Az−Ax| 的问题解决竞赛编写了一个程序在成对不同的有效索引 (x,y,z) 的所有三元组上。该程序具有以下限制:

当我尝试 运行 时出现以下错误 - “在抛出 'std::bad_alloc' what() 实例后调用终止:std::bad_alloc” 。从回答的问题中我所能弄清楚的是我的代码遇到了内存分配问题,但我找不到它在何时何地发生?也许当它处理大值时?是什么导致了错误?

#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef vector<ll> vll;
typedef vector<int> vi;

#define rep(i, a, b) for (ll i = a; i < b; i++)
#define repi(i, a, b) for (ll i = a; i <= b; i++)
#define repn(i, a, b) for (ll i = a; i >= b; i--)
#define fast()                        \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL);                    \
    cout.tie(NULL)
#define all(x) (x).begin(), (x).end()
// solve() function
void solve()
{
    ll n;
    cin >> n;
    vll v(n);
    rep(i, 0, n)
            cin >>
        v[i];
    sort(all(v));
    ll x = v[0], y = v[1], z = v[n - 1];
    ll ans = abs(x - y) + abs(y - z) + abs(z - x);
    cout << ans << endl;
}
// driver function
int main()
{
    fast();
    ll t = 1;
    cin >> t;
    rep(i, 0, t)
    {
        solve();
    }
    return 0;
}

输入格式如下:

Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1, A2,…,AN.

以下是示例输入:

3
3
2 7 5
3
3 3 3
5
2 2 2 2 5

你必须这样做:我没有通过 cin 获取数据,我只是指定值。

void solve()
{
    ll n =100000000; 
    vll v;
    v.reserve(n);
    //omitted
}

它运行良好,并且不会抛出 bad_alloc 错误。在您的情况下, n 可能未初始化,并且未获得有效输入,因此它传递的 n 非常大。当 vll v(n) 尝试分配它时内存不足,而 returns 137 则意味着内存不足。所以它失败了。如果您直接在 vector 的构造函数中指定 n ,它将分配更多内存(取决于编译器)。但是如果你保留你需要的内存,它可以正常工作,直到你有足够的内存来保存你放在 vector.

中的数据。