我已编写代码来测试两个数组中存在多少相同的数字,但由于某种原因,它会抛出&#st; :: bad_alloc'有谁能解释为什么?由于某种原因它只在N = 1000000时抛出它,是因为我已经分配了4000000字节的内存?
以下是代码:
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <math.h>
#include <iomanip>
using namespace std;
int find_last_before_zero(const vector<int>& vec) {
for (int i = vec.size() - 1; i >= 0; --i) {
if (vec[i] != 0) return i + 1;
}
return vec.size();
}
void gen_random_array(vector<int>& vec){
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dist(100000, 100200);
for(int i = 0; i < vec.size(); ++i){
vec[i] = dist(gen);
}
}
void binSearchClient(int T){
int counters[4] = {0,0,0,0};
string names[4] = {"for n = 1000 = ", "for n = 10000 = ", "for n = 100000 = ", "for n = 1000000 = "};
for(int i = 0; i < T; ++i){
int N = 1000;
for(int k = 0; k < 4; ++k){
N *= pow(10.0, k);
vector<int> first(N), second(N);
gen_random_array(first, N); gen_random_array(second, N);
vector<int> intersection(N);
sort(first.begin(), first.end()); sort(second.begin(), second.end());
set_intersection(first.begin(), first.end(), second.begin(), second.end(), intersection.begin());
counters[k] += find_last_before_zero(intersection);
}
}
}
}
for(int i = 0; i < 4; ++i){
cout << names[i] << setprecision(10) << std::fixed << (1.0 * counters[i]) / T << endl;
}
}
int main(){
binSearchClient(1);
}
答案 0 :(得分:4)
在第一次迭代中,您将N设为1000.然后在for(int k = 0; k < 4; ++k)
中执行N *= pow(10.0, k);
。因此,对于第一次迭代N = 1000 (N(1000) * 10^0)
k变为1而你N = 10000 (N(1000) * 10^1)
。然后k变为2且N = 1,000,000 (N(10000) * 10^2)
。在k = 3时,你得到的N = 1,000,000,000,000,000 (N(1,000,000) * 10^3)
很可能是你可以分配的内存。