Reputation: 13
Is it possible to iterate over both dimensions of a struct? Being more specific, I was wondering wheather it is possible to iterate over the columns of a struct such as:
struct Struct { string NAME; int WERT; double VALUE; datetime TIME; int INT; string TYPE; };
Struct s[];
string cols[]={"NAME","WERT","VALUE","TIME","INT","TYPE" };
s[0].NAME = "B";
s[0].WERT = 10;
s[0].VALUE= 50.00;
s[0].TIME = TimeCurrent();
s[0].INT=5;
s[0].TYPE="Man";
s[1].NAME = "A";
s[1].WERT = 10000;
s[1].VALUE= 40000.00;
s[1].TIME = TimeCurrent();
s[1].INT=100;
s[1].TYPE="female";
for(int i=0; i<3; i++)
{
for(int j=0; j<=ArraySize(cols); j++)
{
s[i].cols[j]; // <-------------------
}
}
Upvotes: 0
Views: 600
Reputation: 3012
You can actually use the JAson
library for this type of behavior. linky
Example:
#include <jason.mqh>
void OnStart()
{
CJAVal s;
s[0]["NAME"] = "B";
s[0]["WERT"] = 10;
s[0]["VALUE"]= 50.00;
s[0]["TIME"] = (int)TimeCurrent();
s[0]["INT"]=5;
s[0]["TYPE"]="Man";
s[1]["NAME"] = "A";
s[1]["WERT"] = 10000;
s[1]["VALUE"]= 40000.00;
s[1]["TIME"] = (int)TimeCurrent();
s[1]["INT"]=100;
s[1]["TYPE"]="female";
Print(s.Serialize());
for(int i=0; i<s.Size(); i++) {
for(int j=0; j<s[i].Size(); j++) {
string key = s[i].m_e[j].m_key;
printf("%s = string(%s), int(%d), double(%.3f)",
key,
s[i][key].ToStr(),
s[i][key].ToInt(),
s[i][key].ToDbl()
);
}
}
}
Although, you're much better off creating a to_string
method on your structs
and classes
struct Struct {
string name;
int wert;
double value;
string str() {
return StringFormat("Struct(%s, %d, %.2f)", name, wert, value);
}
};
Upvotes: 0
Reputation: 4691
Welcome to SOF!
First of all, it is better to avoid using complex structures such as string
's inside the struct
. Use class
'es if you want your structures to have string
values. Use an char[]
and convert if you really need a string
in it.
Second, You cannot know how much elements you have inside a struct
and cannot iterate over that - no refrection, sorry. If I were you, I would convert your TYPE
to bool
(enum
in case "male" and "female" is not enough :) and have an array
of long
's (including int
, bool
, datetime
and any other integer types) and double
's (add float
's in it) then iterate over size of those two array
's.
Upvotes: 0