如何从 C 样式数组初始化 std::vector? [英] How to initialize std::vector from C-style array?

查看:29
本文介绍了如何从 C 样式数组初始化 std::vector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 C 样式数组初始化 std::vector 最便宜的方法是什么?

What is the cheapest way to initialize a std::vector from a C-style array?

示例:在下面的类中,我有一个vector,但由于外部限制,数据将作为C风格的数组传入:

Example: In the following class, I have a vector, but due to outside restrictions, the data will be passed in as C-style array:

class Foo {
  std::vector<double> w_;
public:
  void set_data(double* w, int len){
   // how to cheaply initialize the std::vector?
}

显然,我可以调用 w_.resize() 然后遍历元素,或者调用 std::copy().有没有更好的方法?

Obviously, I can call w_.resize() and then loop over the elements, or call std::copy(). Are there any better methods?

推荐答案

不要忘记你可以把指针当作迭代器:

Don't forget that you can treat pointers as iterators:

w_.assign(w, w + len);

这篇关于如何从 C 样式数组初始化 std::vector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆