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

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


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

w_.assign(w, w + len);


You use the word initialize so it's unclear if this is one-time assignment or can happen multiple times.

If you just need a one time initialization, you can put it in the constructor and use the two iterator vector constructor:

Foo::Foo(double* w, int len) : w_(w, w + len) { }

Otherwise use assign as previously suggested:

void set_data(double* w, int len){    w_.assign(w, w + len);}


Well, Pavel was close, but there's even a more simple and elegant solution to initialize a sequential container from a c style array.

In your case:

w_ (array, std::end(array))
  • array will get us a pointer to the beginning of the array (didn't catch it's name),
  • std::end(array) will get us an iterator to the end of the array.