How to copy an array to an STL vector efficiently?

#C++

Consider the following array and std::vector :

std::vector<double> dataVec;  
double              dataArr[] = { 1.0, 2.0, 3.0, 4.0, 5.0 };  
unsigned int        N         = sizeof(dataArr) / sizeof(double); 

Method 1 : Copy the array to the vector using copy and back_inserter

copy(dataArr, dataArr+N, back_inserter(dataVec)); 

It is probably the easiest to understand. Just copy each element from the array and push it into the back of the vector. Alas, it's slow. Because there's a loop (implied with the copy function), each element must be treated individually; no performance improvements can be made based on the fact that we know the array and vectors are contiguous blocks.

Method 2 : Same as 1 but pre-allocating the vector using reserve

dataVec.reserve( N ); 
copy(dataArr, dataArr+N, back_inserter(dataVec)); 

It is a suggested performance improvement to Method 1; just pre-reserve the size of the array before adding it. For large arrays this might help. However the best advice here is never to use reserve unless profiling suggests you may be able to get an improvement (or you need to ensure your iterators are not going to be invalidated). Bjarne agrees. Incidentally, I found that this method performed the slowest most of the time though I'm struggling to comprehensively explain why it was regularly significantly slower than method 1...

Method 3 : Copy the array to the vector using memcpy

dataVec.resize( N ); 
memcpy( dataVec.begin(), dataArr, N*sizeof(double) ); 

It is the old school solution - throw some C at the problem! Works fine and fast for POD types. In this case resize is required to be called since memcpy works outside the bounds of vector and there is no way to tell a vector that its size has changed. Apart from being an ugly solution (byte copying!) remember that this can only be used for POD types. I would never use this solution.

Method 4 : vector::insert

dataVec.insert(dataVec.end(), dataArr, dataArr+N); 

It is the best way to go. Its meaning is clear, it is (usually) the fastest and it works for any objects. There is no downside to using this method for this application.

Method 5: Vector initializer and insert

std::vector<double> dataVecTemp( dataArray, dataArray+N ); 
dataVec.insert(dataVec.end(), dataVecTemp.begin(), dataVecTemp.end()); 

It is a tweak on Method 4 - copy the array into a vector and then append it. Good option - generally fast and clear.

Method 6: Vector initializer and assignment

std::vector<double> dataVecTemp( dataArray, dataArray+N ); 
dataVec = dataVecTemp; 

It is a tweak on Method 5 - copy the array into a vector and then append it.