jeudi 16 avril 2015

Why does the following code throw std::bad_alloc?

I have written code to test how many of the same numbers are present in both arrays, but for some reason it throws 'std::bad_alloc' could anyone explain why? It only throws it when N = 1000000 for some reason, is it because I have allocated 4000000 bytes of memory?


Here's the code:



#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <math.h>
#include <iomanip>

using namespace std;

int binary_search_helper(const vector<int>& vec, int lo, int hi, int val){
int mid;
while(lo <= hi){
mid = lo + (hi - lo) / 2;
if(val > vec[mid]) lo = mid + 1;
else if(val < vec[mid]) hi = mid - 1;
else {
return mid;
}
}
return -1;
}

int foo_binary_search(vector<int>& vec, int val){
//sort(vec.begin(), vec.end());
return binary_search_helper(vec, 0, vec.size() - 1, val);
}

void gen_random_array(vector<int>& vec){
random_device rd;
mt19937 gen(rd());
uniform_int_distribution<> dist(100000, 100200);

//for_each(vec.begin(), vec.end(), dist(gen));
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); gen_random_array(second);
sort(first.begin(), first.end()); sort(second.begin(), second.end());

vector<int> uniqueA(N);
copy(first.begin(), first.end(), uniqueA.begin());

vector<int>::iterator lastIt = unique(uniqueA.begin(), uniqueA.end());
int lastPos = lastIt - uniqueA.begin();
for(int j = 0; j < lastPos; ++j){
if(foo_binary_search(second, uniqueA[j]) != -1){
int inFirst = count(first.begin(), first.end(), uniqueA[i]);
int inSecond = count(second.begin(), second.end(), uniqueA[i]);
counters[k] += min(inFirst, inSecond);
}
}
}
}
for(int i = 0; i < 4; ++i){
cout << names[i] << setprecision(10) << std::fixed << (1.0 * counters[i]) / T << endl;
}
}

int main(){
binSearchClient(1);
}

Aucun commentaire:

Enregistrer un commentaire