1

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?

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
Shihao Xu
  • 1,160
  • 2
  • 10
  • 23
  • Another option is `vector course_vector = {"Linux"s, "C++"s, "HTML"s};` – M.M Jan 20 '16 at 11:37
  • using ctor-initializer for `name` is better than default-construction followed by assignment – M.M Jan 20 '16 at 11:38

3 Answers3

5

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

101010
  • 41,839
  • 11
  • 94
  • 168
  • so what do extra braces means ? – Shihao Xu Jan 20 '16 at 11:40
  • [Here](http://stackoverflow.com/questions/11734861/when-can-outer-braces-be-omitted-in-an-initializer-list)'s a really good explanation of omission of outer braces for interested readers. – erip Jan 20 '16 at 11:40
2

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.

Marko Popovic
  • 3,999
  • 3
  • 22
  • 37
  • well that or do `vector course_vector = {"Linux"s, "C++"s, "HTML"s, "HTML5"s};` if he has a compiler with `std::string` literal support – PeterT Jan 20 '16 at 11:28
0

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

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