简体   繁体   中英

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<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()

Update: Do not forget to remove empty () to avoid vexing parse

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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