1

I initialized a vector in my c++ program, then reserved some memory to store values in it. Why I can't assign value to the memory block I had reserved earlier?

vector<int> test;
test.reserve(100);
test[36] = -234;

This doesn't work too:

vector<int> test;
test.reserve(100);
test = {1};
test[1] = -234;

In both cases it raises the same exception: vector subscript out of range.

Please help me, thanks very much!

Firegreat
  • 44
  • 4
  • There is no thing as "insertion with []" for a vector. With reserve, you only allocate memory. The size of the vector is still 0. So if you try to access any element in the vector, you're accessing a non constructed element – JHBonarius Oct 16 '22 at 08:41
  • The `reserve` call might allocate memory, but the *size* is still zero. Which means any indexing will still be *out of bounds* and lead to *undefined behavior*. What does your text-books or tutorials tell you about the difference between a vectors *capacity* and its *size*? – Some programmer dude Oct 16 '22 at 08:41
  • 1
    `reserve` != `resize`. An empty vector with reserved size is still empty. – Retired Ninja Oct 16 '22 at 08:41

2 Answers2

3

Note that reserve()1 doesn't size the array, it just reserves memory so that as you're inserting with things like push_back it doesn't have to allocate as frequently, if at all.

You'll need to resize() it to do be sure the entries exist, or allocate it already sized as you need:

vector<int> test(100);

test[36] = -264;

--

1 You'll see reserve() used with shrink_to_fit() in code that has a really good idea of how many entries there are going to be after some operation, but isn't entirely sure. If you know exactly, state that up front in the constructor to save the hassle of making a zero-length one, then immediately resizing it.

tadman
  • 208,517
  • 23
  • 234
  • 262
1

reserve does just what it says it does. It 'reserves' the memory, meaning that you can insert up to 100 elements without the underlying structure resizing.

What you want is resize, which actually constructs these 100 elements and allows you to access (and change) the elements with [].

Refugnic Eternium
  • 4,089
  • 1
  • 15
  • 24