L
luigi
Hi,
I am trying to speed up the perfomance of stl vector by
allocating/deallocating blocks of memory manually. one version of the
code crashes when I try to free the memory. The other version seem to
work. I would appreciate someone to comment on this.
Version 1 (crashes on deallocating)
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
vector<double *> vec;
double *ary1 = new double[5];
for(int i=0;i<5;i++)
{
vec.push_back(&ary1);
}
double *ary2 = new double[5];
for(i=0;i<5;i++)
{
vec.push_back(&ary2);
}
for(i=0;i<vec.size();i++)
*vec=double(i);
for(i=0;i<vec.size();i++)
cout << *vec << endl;
// crash!!
for(i=0;i<vec.size();i++)
{
double *p = vec;
delete p; // free each element, one at a time
}
}
Version 2: seem to work, but is it good?
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
vector<double *> tab;
vector<double *> vec;
double *ary1 = new double[5];
for(int i=0;i<5;i++)
{
vec.push_back(&ary1);
}
tab.push_back(ary1);
double *ary2 = new double[5];
for(i=0;i<5;i++)
{
vec.push_back(&ary2);
}
tab.push_back(ary2);
for(i=0;i<vec.size();i++)
*vec=double(i);
for(i=0;i<vec.size();i++)
cout << *vec << endl;
for(i=0;i<tab.size();i++)
delete [] tab; // delete as two arrays
for(i=0;i<vec.size();i++)
{
cout << vec << endl;
}
for(i=0;i<vec.size();i++)
{
cout << *vec << endl;
}
}
I am trying to speed up the perfomance of stl vector by
allocating/deallocating blocks of memory manually. one version of the
code crashes when I try to free the memory. The other version seem to
work. I would appreciate someone to comment on this.
Version 1 (crashes on deallocating)
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
vector<double *> vec;
double *ary1 = new double[5];
for(int i=0;i<5;i++)
{
vec.push_back(&ary1);
}
double *ary2 = new double[5];
for(i=0;i<5;i++)
{
vec.push_back(&ary2);
}
for(i=0;i<vec.size();i++)
*vec=double(i);
for(i=0;i<vec.size();i++)
cout << *vec << endl;
// crash!!
for(i=0;i<vec.size();i++)
{
double *p = vec;
delete p; // free each element, one at a time
}
}
Version 2: seem to work, but is it good?
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
vector<double *> tab;
vector<double *> vec;
double *ary1 = new double[5];
for(int i=0;i<5;i++)
{
vec.push_back(&ary1);
}
tab.push_back(ary1);
double *ary2 = new double[5];
for(i=0;i<5;i++)
{
vec.push_back(&ary2);
}
tab.push_back(ary2);
for(i=0;i<vec.size();i++)
*vec=double(i);
for(i=0;i<vec.size();i++)
cout << *vec << endl;
for(i=0;i<tab.size();i++)
delete [] tab; // delete as two arrays
for(i=0;i<vec.size();i++)
{
cout << vec << endl;
}
for(i=0;i<vec.size();i++)
{
cout << *vec << endl;
}
}