1

So I have a vector, that is initally empty, but is surelly gone get filled. It contains instances of structure:

struct some {
    int number;
    MyClass classInstance;
}

/*Meanwhile later in the code:*/
vector<some> my_list;

When it happens, the I want to add value to vector, I need to enlarge it by one. But of course, I don't want to create any variables to do it. Without this requested, I'd do this:

//Adding new value:
some new_item;       //Declaring new variable - stupid, ain't it?
my_list.push_back(new_item); //Copying the variable to vector, now I have it twice!

So, instead, I want to create the new_item within the vector by increasing its size - have a look:

int index = my_list.size();
my_list.reserve(index+1);  //increase the size to current size+1 - that means increase by 1
my_list[index].number = 3;  //If the size was increased, index now contains offset of last item

But this does not work! It seems that space is not allocated - and I get vector subscript out of range error.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778

3 Answers3

5
my_list.reserve(index+1); // size() remains the same 

Reserve doesn't change my_list.size(). It just increases the capacity. You are confusing this with resize:

my_list.resize(index+1);  // increase size by one

See also Choice between vector::resize() and vector::reserve() .

But I recommend another way:

my_vector.push_back(some());

The additional copy will be elided from your compiler, so there is no overhead. If you have C++11, you can do that more elegant by emplacing into the vector.

my_vector.emplace_back();
Community
  • 1
  • 1
ipc
  • 8,045
  • 29
  • 33
  • I'm very carefull when using `new`. Should I call both `.reserve` (to allocate) and `.resize` (to resize)? – Tomáš Zato Mar 17 '13 at 22:18
  • Use reserve only if you insert many values into the vector. `resize` is very smart and increases the capacity by a constant factor (often 2) to provide a `push_back` in amortized constant time. – ipc Mar 17 '13 at 22:20
2

std::vector::reserve only makes sure enough memory is allocated, it does not increase the size of the vector. You're looking for std::vector::resize.

Also, if you have a C++11 compiler, you can use std::vector::emplace_back to construct the new item in place, thus avoiding a copy.

my_list.emplace_back(42, ... ); // ... indicates args for MyClass constructor
Praetorian
  • 106,671
  • 19
  • 240
  • 328
0

reserve() just asks the allocator for space, but does not actually fill it. Try vector.resize()

DennisL
  • 466
  • 3
  • 6