[英]I am getting bad_alloc error in c++ program
我寫了一個 c++ 程序,但出現錯誤。 我不明白我收到錯誤的原因。 請幫助我解決此問題。
這是我的代碼:
#include <bits/stdc++.h>
#define endl "\n"
#define int long long
using namespace std;
void solve() {
int n, x;
cin >> n >> x;
cout << n << x;
vector <int> in(n);
for (auto &p : in)
cin >> p;
vector<int> vect;
vect = in;
int cnt = 0;
int l = n;
for (int i = 0; i < l; i++) {
if (vect[i] % 2 == 0) {
while (x--) {
vect.push_back(vect[i] / 2);
l++;
}
}
else {
cnt = i;
break;
}
}
int sum = 0;
for (int i = 0; i < cnt; i++) {
sum += vect[i];
}
cout << sum << endl;
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--) {
solve();
}
}
輸入是:
2 1 2 12 4 2 4 6 8 2
這是我在崇高文本中編譯它時遇到的錯誤:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
[Finished in 4.0s]
問題在於變量x
的處理。 不要問我解決方案是什么,但我可以描述問題。
while (x--) {
vect.push_back(vect[i] / 2);
l++;
}
此循環第一次運行x
等於 2。 因此將兩項添加到向量中,並且x
取值-1
。
下次此循環運行時x
從-1
開始,因此循環運行直到您用完 memory 並獲得bad_alloc
異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.