How to initialize std::vector from C-style array?

Frank picture Frank · Mar 12, 2010 · Viewed 134.5k times · Source

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?

Answer

Pavel Minaev picture Pavel Minaev · Mar 12, 2010

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

w_.assign(w, w + len);