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

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

问题描述

什么是初始化最廉价的方式的std ::矢量从C风格的数组?

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

例如:在下面的类,我有一个矢量,但由于外界的限制,该数据将被传递作为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 ::复制()。是否有更好的方法?

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);

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

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