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..
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.
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;
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