Home > Net >  Find size of glm::vec3 array
Find size of glm::vec3 array

Time:06-19

I have this glm::vec3 array and I would like to know the size of the array:

glm::vec3 cubePositions[] = {
        glm::vec3(0.0f,  0.0f,  0.0f),
        glm::vec3(2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3(2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3(1.3f, -2.0f, -2.5f),
        glm::vec3(1.5f,  2.0f, -2.5f),
        glm::vec3(1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
    };  

So far the size is 10 but is there a way to find that in code?

I have tried cubePositions->length() but it only gives me the value 3.

I have tried glm::length(cubePositions) but it doesn't seem like thats how you use the glm::length function. This way gives an error.

Thank you for any help!

CodePudding user response:

cubePositions is a C style array. It decays to a pointer to glm::vec3. See here about array to pointer decay: What is array to pointer decay?.

Therefore when you use cubePositions->length() it's equivalent to using cubePositions[0].length(), which returns the glm length of the first element (i.e. 3 because it's a vec3).

To get the number of elements in the array in this case you can use:

auto num_elements = sizeof(cubePositions) / sizeof(cubePositions[0]);

Note: this will work only in the scope where cubePositions is defined because only there the real size of the array is known. It will no longer work e.g. if you pass cubePositions to another function, because then the array will decay to a pointer and will "loose" it's sizeof.

However - this is not the recomended way to do it in C .
It is better to use std::vector for a dynamic size array. It has a method: size() to retrieve the number of elements:

#include <vector>

std::vector<glm::vec3> cubePositions = {
    glm::vec3(0.0f,  0.0f,  0.0f),
    glm::vec3(2.0f,  5.0f, -15.0f),
    glm::vec3(-1.5f, -2.2f, -2.5f),
    glm::vec3(-3.8f, -2.0f, -12.3f),
    glm::vec3(2.4f, -0.4f, -3.5f),
    glm::vec3(-1.7f,  3.0f, -7.5f),
    glm::vec3(1.3f, -2.0f, -2.5f),
    glm::vec3(1.5f,  2.0f, -2.5f),
    glm::vec3(1.5f,  0.2f, -1.5f),
    glm::vec3(-1.3f,  1.0f, -1.5f)
};

auto num_elements = cubePositions.size();

Note: if your array has a fixed size (known at compile time), you can also use std::array. It also has a size() method, although in this case it is not as useful, as the size cannot change dynamically and is actually one of the template parameters.


Update::
As @HolyBlackCat commented below, it is better to use std::size to get the number of elements in an old C array:

auto num_elements = std::size(cubePositions);

It will not compile if you pass a decayed pointer rather than a real array. Just keep in mind that as I wrote above you'd better avoid old C arrays if you can.

  • Related