2

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?

4

1 回答 1

5

不,恐怕不能在不复制 的情况下将 a 转换valarray为 a 。vector

您的选择是:

  1. 转换您现有的代码库以使用vector,并使用表达式模板来保留valarray.
  2. 转换库以使用valarray.
  3. 复制。

我将从选项 3 开始,然后复制。

于 2016-09-19T10:28:54.063 回答