Home > Backend Development > C++ > body text

How to Quickly Initialize a std::vector from a C-Style Array?

DDD
Release: 2024-11-16 12:09:02
Original
866 people have browsed it

How to Quickly Initialize a std::vector from a C-Style Array?

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template