![](/img/trans.png)
[英]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) 的三元組上。 該程序具有以下約束:
當我嘗試運行它時出現以下錯誤 - "terminate call after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc" 。 從已回答的問題中,我只能弄清楚我的代碼遇到了 memory 分配問題,但我找不到它在何時何地發生的問題? 也許當它處理大值時? 是什么導致了錯誤?
#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)
嘗試分配時,它會用完 memory 並returns 137
,這意味着用完 memory。 所以它失敗了。 如果您將n
直接指定到vector
的構造函數中,它將分配更多內存(取決於編譯器)。 但是,如果您保留所需的 memory ,它可以正常工作,直到您有足夠的 memory 來保存您放入vector
中的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.