Ratnesh
Ratnesh

Reputation: 1700

Initialize the array of struct in c++11

I am facing a problem in initializing an array of struct. Below is the code:

#include <iostream>
#include <array>
#include <string>

#define NUM_ELEMENT 5

struct Person
{
    std::string m_name;
    int m_age = 0;

    Person() = default;
    Person(std::string name, int age)
        : m_name(name), m_age(age) {}
};
typedef std::array<Person, NUM_ELEMENT> PersonList;

class Detail
{
public:
    void InitializePerson();
private:
    PersonList personList;
};

void Detail::InitializePerson()
{   
    personList{                //  <------ Getting Error here..
        Person("abc", 10),
        Person("cde", 20),
        Person("pqr", 30),
        Person("xyz", 40),
        Person("apple", 50),
    };
}

int main()
{
    Detail detail;
    detail.InitializePerson();
    return 0;
}

Though, I know I can use the std::vector with push_back but I want to achive this through the static array as it elements are fixed. I want to initialize the array with above class Detail member and since the data can be random, so not able to do in for loop by personList[0] = Person{};

Upvotes: 2

Views: 713

Answers (3)

Ted Lyngmo
Ted Lyngmo

Reputation: 118077

You are trying to initialize personList which can only be done at construction - but personList is already constructed so that doesn't work. You should be assigning instead:

personList = {
    Person("abc", 10),
    Person("cde", 20),
    Person("pqr", 30),
    Person("xyz", 40),
    Person("apple", 50),
};

alternatively:

personList = {{
    {"abc", 10},
    {"cde", 20},
    {"pqr", 30},
    {"xyz", 40},
    {"apple", 50},
}};

If you want it initialized, you could do that in a Detail constructor:

class Detail {
public:
    Detail() :
        personList{{
            {"abc", 10},
            {"cde", 20},
            {"pqr", 30},
            {"xyz", 40},
            {"apple", 50},
        }}
    {}

private:
    PersonList personList;
};

Upvotes: 1

Benjamin Christoffersen
Benjamin Christoffersen

Reputation: 4841

This seems to do

personList = {{               
        { "abc", 10 },
        { "cde", 20 },
        { "pqr", 30 },
        { "xyz", 40 },
        { "apple", 50 },
    }};

See this answer.

Upvotes: 1

nhatnq
nhatnq

Reputation: 1193

Seems you are missing = operator

personList = {               
    Person("abc", 10),
    Person("cde", 20),
    Person("pqr", 30),
    Person("xyz", 40),
    Person("apple", 50),
};

Upvotes: 1

Related Questions