Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a whole struct at once in an array

Tags:

c++

arrays

struct

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...
like image 469
mohrphium Avatar asked Dec 27 '22 02:12

mohrphium


2 Answers

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.

like image 104
P.P Avatar answered Jan 31 '23 02:01

P.P


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);
like image 36
dialer Avatar answered Jan 31 '23 03:01

dialer