Home > Backend Development > C++ > How to Efficiently Initialize a `std::vector` from a C-style Array?

How to Efficiently Initialize a `std::vector` from a C-style Array?

Patricia Arquette
Release: 2024-11-09 14:22:02
Original
471 people have browsed it

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?
}
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template