在C++中迭代结构
Iterating a struct in C++
我在迭代结构时遇到了一些麻烦。
结构的定义方式不同,具体取决于编译器标志。我想将所有结构成员设置为 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));
相关文章:
- C++结构编译器错误询问向量的迭代器
- 如何使用迭代器指向结构体c++的向量
- 在VS 2017中,朋友通过具有私有析构函数的结构的unique_ptr向量进行迭代失败
- 迭代结构中包含的向量
- 为结构的向量创建C 矢量迭代器
- 是否有一个很好的方法可以在C 11中打印出像JSON一样的Trie结构(仅迭代解决方案)的扁平命名空间
- 有没有办法迭代不完整的结构
- 用于隐藏结构细节的迭代器适配器
- 在 stl 中迭代结构类型的队列
- 无法迭代结构"string"的哈希映射:[列表] C++
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 如何从数据结构的向量中收集迭代器
- 当迭代器添加到添加到列表向量的结构时,迭代器停止指向值?
- 使用POCO迭代JSON结构
- 是否值得两次通过文件进行迭代,以创建最小的数据结构
- 创建自定义迭代器结构以与CSTDIO一起使用
- 在编译时使用模板在跨结构字段中迭代
- 正在取消引用自定义结构字段的迭代器
- 使用C预处理器在结构字段上进行迭代
- 如何列出向量中存储的结构迭代次数