C++ – How to initialize std::vector from C-style array

arrayscstlvector

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

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?
}

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

Best Answer

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

w_.assign(w, w + len);