![](/img/trans.png)
[英]How to fix C++ error: terminate called after throwing an instance of 'std::bad_alloc'. what(): std::bad_alloc
[英]C++ error: terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
我編寫了下面的代碼來執行一些任務。
這是我的代碼:
#include <bits/stdc++.h>
#define MOD 1000000007
using namespace std;
int main() {
int t; cin >> t;
while (t--) {
long long int N; cin >> N;
vector<long long int> cars(N);
for (long long int i = 0; i < N; ++i) {
cin >> cars[i];
}
sort(cars.begin(), cars.end(), greater<long long int>());
long long int profit = 0;
for (long long int i = 0; i < N; ++i) {
if (cars[i]) {
profit += cars[i] - i;
}
}
cout << profit << endl;
}
return 0;
}
我真的不知道為什么我在提交代碼時會遇到這個錯誤。 誰能幫我擺脫困境。 輸入 輸入的第一行包含一個 integer T 表示測試用例的數量。 T 測試用例的描述如下。 每個測試用例的第一行包含一個 integer N。第二行包含 N 個空格分隔的整數 P1、P2、...、PN。 Output 對於每個測試用例,打印一行包含一個 integer —— Chef 可以賺取的最大利潤,模 1,000,000,007。
Constraints
1≤T≤25
1≤N≤105
0≤Pi≤109 for each valid i
The inputs are
2 next line
3 next line
6 6 6 next line
3 next line
0 1 0
Expected Output
15 next line
1
我嘗試了你的代碼中的輸入,它似乎工作正常,你只是錯過了這里需要的標題。 vector , iostream和algorithm ,也許您的代碼沒有問題,您只是在可能具有較小 memory 限制的平台上運行。 您需要專注於優化,但如果您對需要的結果有問題,請提供代碼背后的想法,輸入示例,預期 output,當前 output 以及 t 和 N 的范圍。
檢查: https://stackoverflow.com/help/minimal-reproducible-example
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.