Assigning a std::vector from a C-Style Array
In various scenarios, it becomes necessary to assign a std::vector using a C-style array. Consider the following class with a vector that needs to be initialized using data passed as a C-style array:
class Foo { std::vector<double> w_; public: void set_data(double* w, int len){ // how to cheaply initialize the std::vector? } };
Instead of resizing the vector and iterating over the elements or using std::copy(), a more efficient approach exists. Utilizing the fact that pointers can be treated as iterators, the vector can be quickly assigned using:
w_.assign(w, w + len);
This syntax assigns the range from the pointer w to w len, effectively initializing the vector with the values from the C-style array.
The above is the detailed content of How to Quickly Initialize a std::vector from a C-Style Array?. For more information, please follow other related articles on the PHP Chinese website!