Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
Phlox Midas Avatar asked Oct 31 '25 04:10

Phlox Midas


1 Answers

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.

like image 69
Martin Bonner supports Monica Avatar answered Nov 02 '25 19:11

Martin Bonner supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!