I have a subfunction that reads a data stream and creates an array of vertex data based on that. The main function calls this subfunction repeatedly and updates the vertex data array, which is then bound to a buffer and drawn. So far, so good. However, I cannot figure out how to add vertices. C++ does not let you reassign or resize entire arrays. I can't use vectors because the OpenGL functions take in arrays, not vectors.
2 Answers
You can use vectors to populate an OpenGL vertex buffer. The values in a vector
are guaranteed to be contiguous. See for example these discussions for details on the related language standards:
- Are std::vector elements guaranteed to be contiguous?
- Is it safe to assume that STL vector storage is always contiguous?
This means that code like the following is safe:
std::vector<GLfloat> vertexPositions;
// Populate vector with vertex positions.
GLuint bufId = 0;
glGenBuffers(1, &bufId);
glBindBuffer(GL_ARRAY_BUFFER, bufId);
glBufferData(GL_ARRAY_BUFFER, vertexPositions.size() * sizeof(GLfloat),
&vertexPositions[0], GL_STATIC_DRAW);
The subtle but critical part is that you pass in the address of the first element of the vector, not the address of the vector object.

- 1
- 1

- 53,228
- 8
- 93
- 133
-
Interesting. Coming from a Java background, I didn't immediately recognize the vector -> pointer<->array path. Thanks. – user2258552 Jun 05 '14 at 19:21
I would make a slight edit. While you can use &vertexPositions[0] as the address of the beginning of an STL vector, I prefer to use the function designed to return the address of the beginning of the vector memory, vertexPositions.data().
std::vector<GLfloat> vertexPositions;
// Populate vector with vertex positions.
GLuint bufId = 0;
glGenBuffers(1, &bufId);
glBindBuffer(GL_ARRAY_BUFFER, bufId);
glBufferData(GL_ARRAY_BUFFER, vertexPositions.size() * sizeof(GLfloat), vertexPositions.data(), GL_STATIC_DRAW);
I use STL vectors for OGL data for a number of reasons. It's easy to preallocate if you know the size, and they will grow (and stay contiguous) when you add items. They are easy to iterate through. You can easily create vectors of structures if you want to pass in interleaved data. It all works the same.

- 61
- 1
- 1
-
I didn't use the `data()` method in the answer since it was only introduced in C++11, while the other approach works with all versions of C++. In any case, this looks more like a comment than an answer. – Reto Koradi Jun 05 '14 at 06:58