Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate memory for a vector [closed]

Tags:

c++

vector

Can someone give me an example of how to allocate memory for a vector? A couple of lines is all I need. I have a vector that takes in 20-30 elements.. but when i try to cout it and compile it i only get the first couple of entries..

like image 422
Prasanth Madhavan Avatar asked Sep 02 '25 05:09

Prasanth Madhavan


2 Answers

An std::vector manages its own memory. 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.

std::vector<int> vec2;
vec2.resize(30);  // Allocate space for 30 items, and vec2 now contains 30 items.
like image 123
Frédéric Hamidi Avatar answered Sep 04 '25 19:09

Frédéric Hamidi


Take a look at this You use list.reserve(n);

Vector takes care of its memory, and you shouldn't really need to use reserve() at all. Its only really a performance improvement if you already know how large the vector list needs to be.

For example:

std::vector<int> v;
v.reserve(110); // Not required, but improves initial loading performance

// Fill it with data
for(int n=0;n < 100; n++)
    v.push_back(n);

// Display the data
std::vector<int>::iterator it;
for(it = v.begin(); it != v.end(); ++it)
    cout << *it;
like image 41
Simon Hughes Avatar answered Sep 04 '25 18:09

Simon Hughes