Getting array pointer from std :: vector <glm :: vec3> with type float

I have std::vector<glm::vec3>, and I want to get an array pointer from it with type float.

If the contents of std :: vector would be:

std::vector[0] = vec3(0.1f, 0.2f, 0.3f)
std::vector[1] = vec3(0.4f, 0.5f, 0.6f)
std::vector[2] = vec3(0.7f, 0.8f, 0.9f)

Then this is what will return the pointer of the array with the specified current index:

array[0] = 0.1f
array[1] = 0.2f
array[2] = 0.3f
array[3] = 0.4f
array[4] = 0.5f
array[5] = 0.6f
array[6] = 0.7f
array[7] = 0.8f
array[8] = 0.9f

If possible, what is the most common way to achieve it?

+3
source share
2 answers
std::vector<glm::vec3> vec;
vec.push_back(glm::vec3(0.1f, 0.2f, 0.3f));
vec.push_back(glm::vec3(0.3f, 0.4f, 0.5f));
vec.push_back(glm::vec3(0.7f, 0.8f, 0.9f));

float *flat_array = &vec[0].x;

for(int i=0; i<9; i++)
    std::cout << flat_array[i] << std::endl;

Assuming glm :: vec3 contains three tightly packed floats, you can get a pointer to the first element of the first vec. This pointer can be indexed as an array.

Beware if glm :: vec3 contains paired or other member variables. In this case, the magic of the pointer will not work.

+4
source

, glm:: value_ptr, glm/gtc/type_ptr.hpp

std::vector<glm::vec3> vec;
vec.push_back(glm::vec3(0.1f, 0.2f, 0.3f));
vec.push_back(glm::vec3(0.3f, 0.4f, 0.5f));
vec.push_back(glm::vec3(0.7f, 0.8f, 0.9f));

float* flat_array = static_cast<float*>(glm::value_ptr(vec.front()));
std::cout << std::endl;
for (int i = 0; i < vec.size()*(vec.front().length()); ++i ) {
    std::cout << flat_array[i] << std::endl;
}
+1

All Articles