Home > Article > Backend Development > How to Efficiently Initialize a `std::vector` from a C-style Array?
Assigning a std::vector from a C-style Array Efficiently
When encountering the task of initializing a std::vector from a C-style array, it is crucial to consider both efficiency and convenience. This situation arises when external constraints dictate that data be provided in a C-style array format, as illustrated in the following class example:
class Foo { std::vector<double> w_; public: void set_data(double* w, int len){ // how to cheaply initialize the std::vector? }
To efficiently initialize the std::vector, we can leverage the fact that C-style array pointers can also be treated as iterators. This allows us to avoid creating an intermediate container or looping over individual elements:
Elegant and Efficient Solution:
w_.assign(w, w + len);
Here, w is the pointer to the first element in the C-style array, and w len points to the end of the array. Using the assign function with iterators automatically constructs the vector elements from the array elements. This method is not only efficient but also concise and elegant.
The above is the detailed content of How to Efficiently Initialize a `std::vector` from a C-style Array?. For more information, please follow other related articles on the PHP Chinese website!