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..
Asked
Active
Viewed 1.3e+01k times
28
-
3Do you have any code you could show? The last line of your question really confuses me – default Dec 13 '10 at 10:15
-
2Yes, it sounds like you have made a mistake in your code. You probably shouldn't have to reserve space manually – Dec 13 '10 at 10:27
2 Answers
84
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.

Frédéric Hamidi
- 258,201
- 41
- 486
- 479
-
7to complete this post, `resize()` adds elements constructed with their default constructor (i.e. if the type is `Elem`, then `Elem()`) – swegi Dec 13 '10 at 11:08
-
1@swegi, by default, yes. `resize()` can also take a second argument which will be copied into all the new elements. – Frédéric Hamidi Dec 13 '10 at 11:14
-
1But, if you're just using `.push_back()`, do you have to reallocate/resize? – Charles Dec 10 '15 at 14:29
-
1@c650 If you know how many items there will be and this amount is not a small one then it's better to allocate enough space. – Zbyszek Jul 04 '16 at 06:26
-
4In C++11 you can just pass count in contructor: `std::vector
(1000)`. – Shital Shah Aug 23 '18 at 05:36
9
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;

Community
- 1
- 1

Simon Hughes
- 3,534
- 3
- 24
- 45