Are std::vector elements guaranteed to be contiguous?

前端 未结 7 2117
不知归路
不知归路 2020-11-22 03:41

My question is simple: are std::vector elements guaranteed to be contiguous? In order word, can I use the pointer to the first element of a std::vector as a C-array?

<
相关标签:
7条回答
  • 2020-11-22 04:13

    I found this thread because I have a use case where vectors using contiguous memory is an advantage.

    I am learning how to use vertex buffer objects in OpenGL. I created a wrapper class to contain the buffer logic, so all I need to do is pass an array of floats and a few config values to create the buffer. I want to be able to generate a buffer from a function based on user input, so the length is not known at compile time. Doing something like this would be the easiest solution:

    void generate(std::vector<float> v)
    {
      float f = generate_next_float();
      v.push_back(f);
    }
    

    Now I can pass the vector's floats as an array to OpenGL's buffer-related functions. This also removes the need for sizeof to determine the length of the array.

    This is far better than allocating a huge array to store the floats and hoping I made it big enough, or making my own dynamic array with contiguous storage.

    0 讨论(0)
提交回复
热议问题