如何从 C 样式数组初始化 std::vector?

如何从 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);