用于遍历结构成员(如数组)的 C 方法? [英] C method for iterating through a struct's members like an array?

查看:19
本文介绍了用于遍历结构成员(如数组)的 C 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个矢量类:

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

但是,我希望能够在不将其转换为浮点数组的情况下对其进行迭代.虽然在这种情况下可以接受强制转换,但我很想知道在纯 C 中是否可以使用类似 C++ 的功能.例如,在 C++ 中,因为 std::vectorstd::vectorstd::vectorstd::vectorT > 具有重载的下标 [] 运算符,我可以将其第一个索引的地址传递给采用 void* 的函数.

But, I would like to be able to iterate through it without converting it to an array of floats. While a cast is acceptable in this case, I'm curious to see if anything along the lines of C++ like functionality is doable in straight C. For example, in C++, since std::vector< T > has the subscript [] operator overloaded, I can pass the address of its first index to a function taking a void*.

即,

void do_something_with_pointer_to_mem( void* mem )
{
    // do stuff
}

int main( void )
{
    std::vector< float > v;

    // fill v with values here

    // pass to do_something_with_pointer_to_mem

    do_some_with_pointer_to_mem( &v[ 0 ] );

    return;
}

另一个更具体的例子是当调用 glBufferData(...) 是在 OpenGL 中制作的(使用 C++ 时):

Another, more concrete example is when calls to glBufferData(...) are made in OpenGL (when using C++):

glBufferData(GL_ARRAY_BUFFER, sizeof(somevector), &somevector[0], GL_STREAM_DRAW);

那么,是否有可能在 C 中使用下标运算符完成类似的事情?如果没有,我必须编写一个函数(例如,float vec3_value_at(unsigned int i)),将它放在头文件中是否有意义?定义在?

So, is it possible to accomplish something similar in C using the subscript operator? If not, and I had to write a function (e.g., float vec3_value_at( unsigned int i )), would it make sense to just static inline it in the header file it's defined in?

推荐答案

如果你所有的结构体字段都是同一类型,你可以使用联合如下:

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;

通过这种方式,您可以独立访问每个 x、y 或 z 字段,或者使用 vect3_a 数组对其进行迭代.这个解决方案在内存或计算方面没有任何成本,但我们可能距离类似 C++ 的解决方案有点远.

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.

这篇关于用于遍历结构成员(如数组)的 C 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆