Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 916
user2399378 Avatar asked May 30 '13 13:05

user2399378


People also ask

How do you allocate a vector space?

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.

How are vectors stored in memory?

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.

Is vector allocated in heap?

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 .

How much memory does a vector use?

So there is no surprise regarding std::vector. It uses 4 bytes to store each 4 byte elements.


1 Answers

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
like image 136
juanchopanza Avatar answered Sep 20 '22 00:09

juanchopanza