C ++-为std :: vector <double>创建新的构造函数吗?

用户422005

我编写了一个包含std::vector<double>实例的自定义容器类-效果很好。为了与其他API兼容,我想将容器的内容导出为std::vector<double>copy。目前这有效:

MyContainer container;
....
std::vector<double> vc(container.begin(), container.end());

但是如果可能的话希望能够写:

MyContainer container;
....
std::vector<double> vc(container);

我可以(轻松)创建这样的std::vector<double>构造函数吗?

右折

您可以将显式转换为std::vector<double>

explicit operator std::vector<double>() const {
    return std::vector<double>(begin(), end());
}

然后,std::vector<double> vc(container);将调用std::vector<double>move构造函数。

注意,通常不赞成在计算上昂贵的转换。因此,向量工厂函数可能是一个更明智的方法:

class MyContainer {
public:
    using value_type = double;
    // ...
};

template<typename Source>
auto to_vector(Source source) {
    return std::vector<typename Source::value_type>(source.begin(), source.end());
}

然后你会写:

MyContainer container;
// ...
auto vc = to_vector(container);

这也是更通用的,因为它与任何有兼容的工作value_typebeginend成员。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为std :: vector <struct>创建getter函数

C ++复制构造函数vs移动std :: vector的构造函数

为什么 std::vector<double> v{unsigned int} 没有选择有效的构造函数?

为什么std :: accumulate函数显示错误的vector <double>和?

C++ - 构造函数中的 std::vector 初始化

为什么不能在C ++中为std :: vector的字符串文字初始值设定项列表创建std :: vector <std :: string>?

C++ sort vector<double> vs vector<Object> 以双成员变量为键

创建没有复制构造函数的std :: vectors的std :: vector

C ++中的Double Vector问题

C ++概念为我的类型看到了一个函数,但没有为std :: vector看到它

将std :: vector <std :: vector <std :: string >>转换为std :: vector <std :: vector <double >>

std :: vector默认构造函数可以抛出异常吗

C ++模板函数,可以采用Eigen :: vector或std :: vector

稍后通过调用Class构造函数创建std :: vector <Class>

C ++-创建带有赋值且未初始化的vector <vector <double >>矩阵

std :: vector的C ++钳位函数

C ++函数的可选std :: vector参数

在类构造函数中设置std :: vector,为元素构造函数使用不同的值

C ++-vector <>中的std :: unique_ptr为nullptr

使用std::vector 创建矩阵类,如何在构造函数中设置std::vector 的大小?

用恒定值填充std :: vector <double>

为构造的std :: vector中的每个元素调用默认构造函数

如何在构造时为std :: vector保留内存?

为c样式的字符串创建std :: initializer_list构造函数

std :: vector <double>借用double的内容的标准方法[]

参加std :: vector C ++

使用新的C ++ 11 std :: async加速std:.vector填充

使用boost :: spirit解析为vector <vector <double >>

可能吗?std :: vector <double> my_vec(sz); 已分配但未初始化或填充的