C++11/C++14 initializer_list - 2017
"If you're an experienced C++ programmer and are anything like me, you initially
approached C++11 thinking, "Yes, yes, I get it. It's C++, only more so.".
- Effective Modern C++ by Scott Meyers
When we want to initialize a vector, we had to do the following:
// C++03 std::vector
v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4);
Now, with C++ 11, we can do this:
// C++11 std::vector
v = { 1, 2, 3, 4 };
C++11 binds the concept to a template, called std::initializer_list. This allows constructors and other functions to take initializer-lists as parameters:
#include <iostream> #include <vector> class MyNumber { public: MyNumber(const std::initializer_list<int> &v;) { for (auto itm : v) { mVec.push_back(itm); } } void print() { for (auto itm : mVec) { std::cout << itm << " "; } } private: std::vector<int> mVec; }; int main() { MyNumber m = { 1, 2, 3, 4 }; m.print(); // 1 2 3 4 return 0; })