C法通过一个结构的成员进行迭代像一个数组? [英] C method for iterating through a struct's members like an array?

查看:155
本文介绍了C法通过一个结构的成员进行迭代像一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个向量类:

Let's say I have a vector class:

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

不过,我希望能够通过它来遍历无需将其转换为float数组。虽然投在这种情况下是可以接受的,我很好奇,看看是否沿着C的行++类的东西的功能是可行的直C.例如,在C ++中,因为的std ::矢量< T> 具有标 [] 操作符重载,我可以通过它的第一个索引到一个函数采取无效* 。

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类似的东西?如果没有,我只好写一个函数(例如,浮动vec3_value_at(无符号整型我)),这将是有意义的只是静态内联它在头文件,它的定义?

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天全站免登陆