If I have created a class like this:
struct test{
int a;
int b;
string c;
};
and wanted to iterate through each data member as if it was an array how could i do it?(Assuming the number of members may change in a future update.)
If I have created a class like this:
struct test{
int a;
int b;
string c;
};
and wanted to iterate through each data member as if it was an array how could i do it?(Assuming the number of members may change in a future update.)
Immediately, I note that C ++ does not support arrays of elements of different types, so there is no solution in your case. But with identical members you can create an array of pointers to members and use it in the loop:
struct test {
int a0 = 0;
int a1 = 1;
int a2 = 2;
int a3 = 3;
virtual ~test() {};
};
int main()
{
test t;
int* ptr[4] = { &t.a0, &t.a1, &t.a2, &t.a3 };
for (int i = 0; i < sizeof(ptr) / sizeof(int*); i++)
std::cout << *ptr[i] << std::endl;
return 0;
}