My class dynamically allocates an array of integers (in the code below named this_data), but the array can only be filled up to a maximum length (this_data_maxlen). I would like to add data (add_data) to the array, but the adding array could exceed the maximum length.
Knowing that there is no reallocate for new keywords, I wrote one version that uses memcpy and another version that uses vector, as that was suggested to be the most efficient way. However when testing, the vector version turns out the be 5 times slower than the memcpy. Am I doing something wrong in the vector version?
Memcpy version:
unsigned int this_data_len=50;
unsigned int this_data_maxlen=70; //maximum length of existing dataset
unsigned int add_data_len=50;
int *this_data = new int[this_data_len]; //existing dataset
int *add_data = new int[add_data_len]; //data we want to add to existing dataset
//function here that puts values in them
unsigned int new_data_len=min(this_data_maxlen,this_data_len+add_data_len); //calculate the new dataset length (=7)
int *new_data=new int[new_data_len]; //create the new dataset
//build the new 'this_data'
memcpy(new_data,this_data,this_data_len*sizeof(int)); //copy existing dataset values to new dataset
memcpy(new_data+this_data_len,add_data,(this_data_maxlen-this_data_len)*sizeof(int)); //fill up the new dataset with a selection of the data to add
delete [] this_data; //remove original dataset
this_data=new_data; //set the new dataset
//build the new 'add_data'
add_data_len=add_data_len-(this_data_maxlen-this_data_len); //update the add_data length (=2)
new_data=new int[add_data_len];
memcpy(new_data,add_data+(this_data_maxlen-this_data_len),add_data_len*sizeof(int));
delete [] add_data;
add_data=new_data;
this_data_len=new_data_len; //set the new dataset length
//clean up
delete [] this_data;
delete [] add_data;
Vector version:
unsigned int this_data_len=50;
unsigned int this_data_maxlen=70; //maximum length of existing dataset
unsigned int add_data_len=50;
vector<int> this_vector(this_data_len);
vector<int> add_vector(add_data_len);
//function here that puts values in them
unsigned int new_data_len=min(this_data_maxlen,this_data_len+add_data_len); //calculate the new dataset length (=7)
this_vector.reserve(new_data_len);
this_vector.insert(this_vector.end(),add_vector.begin(),add_vector.begin()+(this_data_maxlen-this_data_len));
add_vector=vector<int>(add_vector.begin()+(this_data_maxlen-this_data_len),add_vector.end());
add_data_len=add_data_len-(this_data_maxlen-this_data_len); //update the add_data length (=2)
this_data_len=new_data_len; //set the new dataset length