+ 5

Array of structures v.s. matrix. What is better?

What is better: array structures with parameters or two-dimensional array of parameters? For example : //firstcode #include<iostream> enum E{health, attack}; using namespace std; int main() { const int size=4; string unit_name[size]; int unit_params[size][2]; for(int i=0;i<size;++i) { unit_params[i][health]=unit_params[i][attack]=i; unit_name="A"; cout<<"Health of warrior "<<unit_name[i]<<" = "<<unit_params[i][health] <<", attack = "<<unit_params[i][attack]<<endl; } }

10th Dec 2016, 10:35 PM
SUPER_S
SUPER_S - avatar
5 Answers
+ 3
//secondcode #include<iostream> using namespace std; struct Unit { int health; int attack; string name="A"; }; int main() { const int size=4; Unit U[size]; for(int i=0;i<size;++i) { U[i].health=U[i].attack=i; cout<<"Health of warrior "<<U[i].name<<" = "<<U[i].health <<", attack = "<<U[i].attack<<endl; } } if I use the first code, it will save size*1 byte of memory (because the struct uses an extra 1 byte of memory as arrays there), but if I use the second code I can more easily operate the units (for example swap()). Which way is more optimal, assuming that I will have to create, store and modify a lot of objects?
11th Dec 2016, 11:33 AM
SUPER_S
SUPER_S - avatar
+ 3
@Fer Yep, I chose structure. It's really easilly!
13th Jan 2017, 4:16 PM
SUPER_S
SUPER_S - avatar
0
What exactly do you mean by that ?
11th Dec 2016, 10:16 AM
Amaras A
Amaras A - avatar
0
Well, I don't know. That is an algorithmic complexity question, and I'm not really good at that kind of things (yet?). But I'd say that you choose: either save execution time, or developer time. Which one do you prefer?
11th Dec 2016, 11:48 AM
Amaras A
Amaras A - avatar
0
I find that structures re much better in this case. First, it looks much cleaner. Second, it's scalable, if you want to add more elements to the structure, you just add it in the definition n refer to it U[i].member. (Sure you can do the same with an array but it's much dirtier and this is what structs are for). and U[i].health seems clearer than U[i][0], doesn't it?
13th Jan 2017, 4:12 PM
Fer