-4

I'm getting a runtime error when trying that scenario, and I get vector subscript out of range

struct Mesh
{
  std::vector<Vertex> mVertices;
}

class Grid
{

public:
Mesh mMesh;
}

Grid g_Grid;

g_Grid.mMesh.mVertices.reserve(40);
g_Grid.mMesh.mVertices[0] = 10; // allocation error 
Ahmed Saleh
  • 2,010
  • 2
  • 35
  • 66

1 Answers1

2

Method reserve does not create elements of a vector. it only reserves memory for elements that can be added to the vector in future with for example method push_back

So write instead

g_Grid.mMesh.mVertices.reserve(40);
g_Grid.mMesh.mVertices.push_back( 10 );

Or if you want that the elements would already exist then write

g_Grid.mMesh.mVertices.resize(40);
g_Grid.mMesh.mVertices[0] = 10;

If you want to add at once several elements to the vector that does not yet contain any elements then you can write

g_Grid.mMesh.mVertices.reserve(40);
g_Grid.mMesh.mVertices = { 10, 20, 30 };
Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303