在C ++中迭代结构

时间:2014-12-16 09:00:35

标签: c++ struct iteration

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

结构可以不同的方式定义,具体取决于编译器标志。 我想将所有struct成员设置为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 ++中轻松完成?

4 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:1)

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

#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函数?如果是这样,这更适合struct的构造函数方法。在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
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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