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.
You can use the reserve() and resize() methods to have it allocate enough memory to fit a given amount of items: std::vector<int> vec1; vec1. reserve(30); // Allocate space for 30 items, but vec1 is still empty.
Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location.
vector has an internal allocator which is in charge of allocating/deallocating memories from heap for the vector element . So no matter how you create a vector, its element is always allocated on the heap .
So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With