在C++中迭代结构

Iterating a struct in C++

本文关键字:结构 迭代 C++      更新时间:2023-10-16

我在迭代结构时遇到了一些麻烦。

结构的定义方式不同,具体取决于编译器标志。我想将所有结构成员设置为 0。我不知道有多少成员,但他们都保证是数字(int,long...

请参阅以下示例:

#ifdef FLAG1
    struct str{
        int i1;
        long l1;
        doulbe d1;
    };
#elsif defined (OPTION2)
    struct str{
        double d1
        long l1;
    };
#else
    struct str{
        int i1;
    };
#endif
我想我想一个

好的伪代码是:

void f (str * toZero)
{
    foreach member m in toZero
        m=0
}

有没有办法在 c++ 中轻松做到这一点?

要在C++中使用= { 0 }将任何 PODO 的数据初始化为零。无需遍历每个成员。

StructFoo* instance = ...
*instance = { 0 };

为简单起见,您可能需要考虑按以下方式使用单个宏:

#define NUMBER_OF_MEMBERS 3
struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1;
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1;
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1;
#endif
};
void f (Str & str){
    #if NUMBER_OF_MEMBERS > 0
        str.i1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 1
        str.d1 = 0;
    #endif
    #if NUMBER_OF_MEMBERS > 2
        str.l1 = 0;
    #endif
    return;
}
int main() {
    Str str;
    f(str);
}

其次,您是否仅在创建类以从零开始值后调用 f 函数? 如果是这样,这更适合结构的构造函数方法。 在 C++11 中,它可以写得像这样干净:

#define NUMBER_OF_MEMBERS 3
struct Str{
#if NUMBER_OF_MEMBERS > 0
    int i1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 1
    double d1 = {0};
#endif
#if NUMBER_OF_MEMBERS > 2
    long l1 = {0};
#endif
};
int main() {
    Str str;
    //no need to call function after construction
}

如果 struct 成员由 定义启用和禁用,那么除了使用相同的定义来访问struct的值之外,没有其他可能性。但是,如果需要灵活性,struct可能不是最佳选择。

你可以使用 C 路,因为它是一个 pod:

memset(&str_instance, '', sizeof(str));