简体   繁体   English

将valarray转换为向量而不进行复制

[英]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. 我有一个非常大的valarray,我需要将其转换为向量,因为我正在使用的库仅将向量作为输入。 I'm wondering if it's possible to convert from valarray to vector without copying. 我想知道是否可以从valarray转换为vector而无需复制。 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.". 有关assign的文档说,该函数“将新内容分配给该向量,替换其当前内容,并相应地修改其大小”。 This sounds to me like it copies. 对我来说听起来像是复制。 Is there a way to do it without copying? 有没有复制的方法吗?

No, I am afraid it is not possible to convert a valarray to a vector without copying. 不,恐怕不复制就无法将valarray转换为vector

Your options are: 您的选择是:

  1. Convert your existing codebase to use vector , and use expression templates to retain most of the benefits of valarray . 将现有的代码库转换为使用vector ,并使用表达式模板保留valarray大部分优点。
  2. Convert the library to use valarray . 将库转换为使用valarray
  3. Copy. 复制。

I would start with option 3 and just copy. 我将从选项3开始,然后复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM