[英]How to correctly initialize a vector of objects in C++?
I am fairly new to C++ and am trying to create a vector of an object and initialize its member, but there is this bit that I'm not sure if I'm doing correctly:我对 C++ 相当陌生,我正在尝试创建一个 object 的向量并初始化它的成员,但是有一点我不确定我是否做得正确:
vector<Card> cardStorage;
for (int i = 0; i < 20; i++) {
Card card;
cardStorage.push_back(card);
}
Basically that is a vector of 20 object of class Card, and push_back takes type Card &, which is pass by reference.基本上这是 class 卡的 20 个 object 的向量,而 push_back 采用 Card & 类型,这是通过引用传递的。 Thus, I am not sure if doing this will yield a vector of 20 different Card objects, or all 20 members of the vector will point at one object, which is not what I want since I will need to traverse through this vector to manipulate the object data member (I also definitely don't want to create 20 object of class Card and push it into the vector, since that's obviously bad practice).
因此,我不确定这样做是否会产生一个包含 20 个不同 Card 对象的向量,或者该向量的所有 20 个成员都将指向一个 object,这不是我想要的,因为我需要遍历这个向量来操作object 数据成员(我也绝对不想创建 class 卡的 20 个 object 并将其推入向量,因为这显然是不好的做法)。
push_back
on a vector
makes a copy of the passed in argument, if the argument is an l-value (an object with a name).如果参数是左值(带有名称的 object),则
vector
上的push_back
会复制传入的参数。 So cardStorage
is guaranteed to have 20 distinct Card
objects in it after the loop is executed, because each Card
is copied into the vector
.所以
cardStorage
保证在循环执行后有 20 个不同的Card
对象,因为每个Card
都被复制到vector
中。
You could consider using emplace_back
to avoid unnecessarily copying the Card
s into the vector
, but you could also simply do:您可以考虑使用
emplace_back
来避免不必要地将Card
复制到vector
中,但您也可以简单地执行以下操作:
vector<Card> cardStorage(20);
which achieves the same effect as the shown code.达到与所示代码相同的效果。
That's fine.没关系。 While
push_back
takes a const-reference (or an rvalue-reference in the overload), your vector holds objects of type Card
.虽然
push_back
采用 const 引用(或重载中的右值引用),但您的向量包含Card
类型的对象。 In this case you'll simply copy the temporary.在这种情况下,您只需复制临时文件。
You could even avoid creating the temporary at all and call emplace_back()
to create the new objects directly in the vector
buffer, or if they're all supposed to be default-constructed, use .resize()
or a constructor that takes the desired size.您甚至可以完全避免创建临时对象并调用
emplace_back()
直接在vector
缓冲区中创建新对象,或者如果它们都应该是默认构造的,请使用.resize()
或采用所需的构造函数尺寸。
Your example is correct.你的例子是正确的。 But it may be more effective.
但它可能更有效。 The most efficient way to init a vector in runtime will be the following (since C++17).
在运行时初始化向量的最有效方法如下(C++17 起)。
vector<Card> cardStorage;
// allocates memory for all the objects
cardStorage.reserve(20);
for (int i = 0; i < 20; i++) {
// constructs the object in-place and returns the reference to that object
// so that you you can do smth with card
auto &card = cardStorage.emplace_back(/*Arguments if needed*/);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.