Shihao Xu
Shihao Xu

Reputation: 1200

What is the easiest way to initialize a std::vector<MyClass> with hardcoded elements?

I wish to create a vector of MyClass, like the following Course class. and I wish to pass an array of string as the names of Courses. So I write

struct Course {
    int id;
    string name;
    static int id_generator;

    Course() {}
    Course(string s);

};

Course::Course(string s) {
    name = s;
    id = id_generator++;
}
int Course::id_generator = 0;

This works

string course_names[] = {"Linux", "C++", "HTML", "HTML5", "NodeJS", "Shell", "Python"};
vector<Course> course_vector(begin(course_names), end(course_names));

but this doesn't

vector<Course> course_vector = {"Linux", "C++", "HTML", "HTML5", "NodeJS", "Shell", "Python"};

error: could not convert ‘{"Linux", "C++", "HTML", "HTML5", "NodeJS", "Shell", "Python"}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<Course>’

why? how to do better?

Upvotes: 1

Views: 547

Answers (3)

Sayan Sarkar
Sayan Sarkar

Reputation: 53

If you are using c++11 or up you can do something like this

std::vector<Course> vec = {Course("course1"), Course("course2"), Course("course3")}; 

Upvotes: 0

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

Aggregate initialization used for aggregate types as arrays:

string course_names[] = {"Linux", "C++", "HTML", "HTML5", "NodeJS", "Shell", "Python"};

Is different to initializer_list initialization. std::vector offers a constructor that takes in a std::initializer_list<T>, and that's the constructor called when you try to initialize a vector with braces. For this to work properly, you need extra braces for each element:

std::vector<Course> course_vector = {{"Linux"}, 
                                     {"C++"},
                                     {"HTML"},
                                     {"HTML5"},
                                     {"NodeJS"},
                                     {"Shell"},
                                     {"Python"}};

Also I it would be better to change your constructor to:

Course::Course(std::string const &s) : id(id_generator++),  name(s) { }

Live Demo

Upvotes: 5

Marko Popovic
Marko Popovic

Reputation: 4153

Add the following constructor:

Course::Course(const char *s) : name(s) {
    id = id_generator++;
}

This way, you will be able to initialize the vector directly, just like you wanted.

Upvotes: 2

Related Questions