我希望創建一個MyClass的矢量,就像下面的課程類一樣。 我希望傳遞一個字符串數組作爲課程名稱。所以我寫使用硬編碼元素初始化std :: vector <MyClass>的最簡單方法是什麼?
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;
這工作
string course_names[] = {"Linux", "C++", "HTML", "HTML5", "NodeJS", "Shell", "Python"};
vector<Course> course_vector(begin(course_names), end(course_names));
但這並不
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>’
爲什麼呢?如何做得更好?
另一種選擇是'vector course_vector = {「Linux」,「C++」,「HTML」s};' –
使用ctor-initializer作爲'name'優於默認構造,其次是賦值 –