Home >Backend Development >C++ >How to Quickly Initialize a std::vector from a C-Style Array?

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

DDD
DDDOriginal
2024-11-16 12:09:02944browse

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?
}
};

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!

Statement:
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