I am learning C++ and I have a problem with struct
and arrays. My struct is:
struct board
{
string name;
string desc;
int nval;
int sval;
int eval;
int wval;
};
My array looks like this:
board field[10][10];
I'm able to do for example:
field[5][6].name = "ExampleName";
field[5][6].desc = "This is an example";
field[5][6].nval = 3;
//and so on...
But I want to assign to the whole structure at once, something like this:
field[5][6] = {"ExampleName", "This is an example", 3, 4, 5, 6};
//so I don't have to type everything over and over again...
What you are trying to do is allowed in C standard. It seems to be working in C++ as well. I verified it in C++11:
struct board
{
string name;
string desc;
int nval;
int sval;
int eval;
int wval;
}field[10][10];
int main()
{
field[5][6]={"ExampleName","This is an example",3,4,5,6};
cout<<field[5][6].name<<endl;
cout<<field[5][6].sval<<endl;
return 0;
}
It's printing correctly. So you should be able to do that.
As has been mentioned, C99 as well as C# support a form of that syntax, but standard C++ doesn't. You could do it with by adding a constructor to your struct. Be aware that this will not be ANSI C compatible anymore.
struct board
{
string name;
string desc;
int nval;
int sval;
int eval;
int wval;
board()
{
}
board(string name, string desc, int nval, int sval, int eval, int wval)
{
this->name = name;
this->desc = desc;
this->nval = nval;
this->sval = sval;
this->eval = eval;
this->wval = wval;
}
};
field[1][2] = board("name", "desc", 1, 2, 3, 4);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With