28

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

Prasanth Madhavan
  • 12,657
  • 15
  • 62
  • 94
  • 3
    Do you have any code you could show? The last line of your question really confuses me – default Dec 13 '10 at 10:15
  • 2
    Yes, 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 Answers2

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