Reputation: 871
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.
Upvotes: 8
Views: 8309
Reputation: 5054
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
Upvotes: 1
Reputation: 227410
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
Upvotes: 14
Reputation: 24596
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 (e.g. have a look here in the "Modifiers" section) and in the C++ beginner's book of your choice.
Upvotes: 1