[英]Vector C++ Memory Allocation
I want to create a vector of elements representing a certain structure. 我想创建一个代表某种结构的元素向量。
The thing is that I don't know how many elements the structure will have, since the number will change very often, and I don't really know how to create a vector. 问题是我不知道结构会有多少元素,因为数字会经常变化,我真的不知道如何创建一个矢量。
How to make that? 怎么做到的?
In order to make it more clear: 为了使它更清楚:
I saw that when creating a vector, you do something like this: 我在创建矢量时看到了这样的事情:
std::vector<structureType> vectorName(nrOfElements);
I don't know the number of elements and what to write there, between brackets. 括号内我不知道元素的数量和在那里写的内容。
If you default construct the vector, you get an empty one: 如果您默认构造向量,则会得到一个空向量:
std::vector<structureType> vectorName; // holds 0 elements
then you can push elements into the vector, increasing its size (see also other vector modifiers ): 然后你可以将元素推入向量,增加其大小(另请参见其他向量修饰符 ):
vectorName.push_back(someStructureTypeInstance);
This might suit your needs. 这可能适合您的需求。 If you are worried about future memory re-allocations, you can use
std::vector::reserve
after constructing the vector. 如果您担心将来的内存重新分配,可以在构造向量后使用
std::vector::reserve
。
std::vector<structureType> vectorName; // holds 0 elements
vectorName.reserve(100); // still 0 elements, but capacity for 100
I don''t know what to write there between brackets
我不知道在括号之间写什么
Write nothing )) In this case you'll create an empty vector, wich could be grown with std::vector::push_back() 什么都不写))在这种情况下,你将创建一个空向量,可以用std :: vector :: push_back()来增长
Update: Do not forget to remove empty ()
to avoid vexing parse 更新:不要忘记删除empty
()
以避免烦恼解析
You can change the number of elements the vector contains, by inserting and/or removing elements. 您可以通过插入和/或删除元素来更改向量包含的元素数。 You are specifically looking for vector's methods
insert
, push_back
/ emplace_back
, resize
, pop_back
, erase
. 你专门寻找vector的方法
insert
, push_back
/ emplace_back
, resize
, pop_back
, erase
。
You'll find descriptions of the methods in any C++ reference (eg have a look here in the "Modifiers" section) and in the C++ beginner's book of your choice. 你会发现在任何C ++参考方法描述(例如看看这里的“调节器”部分中),并在您选择的C ++入门书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.