dimanche 4 janvier 2015

Most efficient way to pass data to a std::valarray from a std::vector

What's the most efficient way to set the data from a std::vector to a std::valarray? Say we have std::valarray<double> my_valarray; and std::vector<double> my_vector; and we want to copy the data across from my_vector to my_valarray:


Option 1 (using valarray constructor and copy assignment):



my_valarray = std::valarray(my_vector.data(), my_vector.size());


Option 2 (resizing and copying):



my_valarray.resize(my_vector.size());
std::copy(my_vector.begin(), my_vector.end(), std::begin(my_valarray));


The question arises because in both cases it looks like the complexity is O(2n). In the first case the data is copied to temporary valarray during construction (one allocation + one pass to copy the data) and then on assignment to the final object (one allocation + one pass to copy the data). In the second case there is one allocation + one pass for initialisation of all elements to zero and another pass to copy the data. Do the move semantic of C++11 applies in the first case making it require only one allocation and one pass to copy the data?


Aucun commentaire:

Enregistrer un commentaire