Phlox Midas Phlox Midas - 2 months ago 9
C++ Question

Converting a valarray to a vector without copying

I have a really large valarray that I need to convert to a vector because a library I'm using only takes a vector as input. I'm wondering if it's possible to convert from valarray to vector without copying. Here's what I have:

#include <vector>
#include <valarray>

int main() {
std::valarray<double> va{ {1, 2, 3, 4, 5} };

//Error: cannot convert from 'initializer list' to 'std::vector<eT,std::allocator<_Ty>>'
//std::vector<double> v1{ std::begin(va), va.size() };

//Error: cannot convert from 'std::valarray<double>' to 'std::vector<eT,std::allocator<_Ty>>'
//std::vector<double> v2{ std::move(va) };

// Works but I'm not sure if it's copying
std::vector<double> v3;
v3.assign(std::begin(va), std::end(va));
}


The documentation on assign says that the function "assigns new contents to the vector, replacing its current contents, and modifying its size accordingly.". This sounds to me like it copies. Is there a way to do it without copying?

Answer

No, I am afraid it is not possible to convert a valarray to a vector without copying.

Your options are:

  1. Convert your existing codebase to use vector, and use expression templates to retain most of the benefits of valarray.
  2. Convert the library to use valarray.
  3. Copy.

I would start with option 3 and just copy.

Comments