c++ - 使用循环填充结构

标签 c++

<分区>

我有一个C++结构

struct Line {
  int date;
  int time;
  float open;
  float high;
  float low;
  float close;
  float sd;
  float long_mo;
  float short_mo;
};

8 个字段。 我想用循环填充它。

int fields_count=1;
while (fields_count<=8) {
  // get digit from outer sourse. I dont need help here.
  // First iteration puts to 1 field, Second iteration puts to 2 field and so on up to last field of struct 
  fields_count++;
}

最佳答案

像这样:

#include<stddef.h>

struct Line {
  int date;
  int time;
  float open;
  float high;
  float low;
  float close;
  float sd;
  float long_mo;
  float short_mo;
};

char types [] = "iifffffff";
int offsets [] = {
  offsetof (Line, date),
  offsetof (Line, time),
  offsetof (Line, open),
  offsetof (Line, high),
  offsetof (Line, low),
  offsetof (Line, close),
  offsetof (Line, sd),
  offsetof (Line, long_mo),
  offsetof (Line, short_mo)
}

Line line;

for (int i = 0; i < 9; i++) {
  char *field_ptr = ((char*)&line) + offsets [i];

  if (types [i] == 'i')
    *(int*)field_ptr = readInt ();
  else if (types [i] == 'f')
    *(float*)field_ptr = readFloat ();
}

关于c++ - 使用循环填充结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55304455/

相关文章:

C++ 设计 : single function performing multiple tasks vs multiple functions performing single task

c++ - 将 boost::asio 集成到基于文件描述符的事件循环中(选择/轮询)

c++ - 创建一个非线程安全的 shared_ptr

c++ - 字符数组是唯一具有某种形式的空终止的类型吗?

c++ - 如何避免必须编写样板访问器代码

c++ - g++小程序中的内部编译器错误

c++ - 使用 Lib3ds 获取顶点数组

c++ - 如何使用 C++ 计算 1-100 数组中的覆盖百分比?

c++ - 通过引用传递 3x3 数组 C++ 错误 : cannot convert ‘double*’ to ‘double’ in initialization

c++ - Visual Studio 中的 std::begin 和 std::end 迭代器