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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5294629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:51:37  来源:igfitidea点击:

Initializing a std::vector with default constructor

c++c++-standard-library

提问by Himadri Choudhury

I have a class field which is a std::vector. I know how many elements I want this vector to contain: N. How do I initialize the vector with N elements?

我有一个类字段,它是 std::vector。我知道我希望这个向量包含多少个元素:N。我如何用 N 个元素初始化向量?

回答by Jerry Coffin

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

回答by James McNellis

std::vectorhas a constructor declared as:

std::vector有一个构造函数声明为:

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

You can use it to construct the std::vectorcontaining Ncopies of x. The default value for xis a value initialized T(if Tis a class type with a default constructor then value initialization is default construction).

你可以用它来构建std::vector包含N的副本x。的默认值x是初始化的值T(如果T是具有默认构造函数的类类型,则值初始化是默认构造)。

It's straightforward to initialize a std::vectordata member using this constructor:

std::vector使用此构造函数初始化数据成员很简单:

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

回答by dappawit

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. 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.

所有允许您指定大小的构造函数也调用元素的构造函数。如果效率至上,您可以使用reserve()成员函数来保留大小。这实际上不会创建任何元素,因此效率更高。不过,在大多数情况下,通过向量构造函数提供大小就可以了。