C method for iterating through a struct's members like an array?

前端 未结 3 1372
不知归路
不知归路 2020-12-10 07:28

Let\'s say I have a vector class:

typedef struct vec3_s
{
    float x, y, z;
}
vec3;

But, I would like to be able to iterate through it wit

3条回答
  •  猫巷女王i
    2020-12-10 08:26

    If all of your structure fields are of the same type, you could use a union as following:

    typedef union vec3_u
    {
        struct vec3_s {
            float x, y, z;
        };
        float vect3_a[3];
    }
    vec3;
    

    This way you could access to each x, y or z field independently or iterate over them using the vect3_a array. This solution cost nothing in term of memory or computation but we may be a bit far from a C++ like solution.

提交回复
热议问题