简体   繁体   English

使用默认构造函数初始化std :: vector

[英]Initializing a std::vector with default constructor

I have a class field which is a std::vector. 我有一个类字段,它是一个std :: vector。 I know how many elements I want this vector to contain: N. How do I initialize the vector with N elements? 我知道我希望这个向量包含多少个元素:N。如何用N个元素初始化向量?

class myclass {
   std::vector<whatever> elements;
public:
   myclass() : elements(N) {}
};

std::vector has a constructor declared as: std::vector有一个构造函数声明为:

vector(size_type N, const T& x = T());

You can use it to construct the std::vector containing N copies of x . 您可以使用它来构造包含Nx副本的std::vector The default value for x is a value initialized T (if T is a class type with a default constructor then value initialization is default construction). x的默认值是初始化为T的值(如果T是具有默认构造函数的类类型,则值初始化是默认构造)。

It's straightforward to initialize a std::vector data member using this constructor: 使用此构造函数初始化std::vector数据成员很简单:

struct S {
    std::vector<int> x;
    S() : x(15) { }
} 

All the constructors that allow you to specify a size also invoke the element's constructor. 允许您指定大小的所有构造函数也会调用元素的构造函数。 If efficiency is paramount, you can use the reserve() member function to reserve the size. 如果效率至关重要,则可以使用reserve()成员函数来保留大小。 This does not actually create any elements, so it is more efficient. 这实际上并不创建任何元素,因此它更有效。 In most cases, though, supplying the size through the vector constructor is just fine. 但是,在大多数情况下,通过向量构造函数提供大小就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM