First you need to turn on the compiler c++11, follow the steps below (codeblocks)
Setting-->compiler the option to tick the red box.
First look at the role of initializer_list, you can use curly braces to initialize the STL container, and can be used in a for loop.
1#include <iostream>2#include <vector>3 using namespacestd;4 5 intMain ()6 {7vector<string> v{"AB","CD"};8vector<string>::iterator begin =V.begin ();9 while(begin!=v.end ())Ten { Onecout << *begin++ <<Endl; A } - for(inti:{1,2,3}) - { thecout << i <<Endl; - } - return 0; -}
The printing results are as follows:
Take a look at the official role:
We can declare initializer_list in the parameters of a function, so that when we call this function, we can pass the curly brace directly to the function. As shown in the following code:
1 #ifndef s_h_included2 #defines_h_included3 4#include <vector>5#include <initializer_list>6#include <iostream>7 8 using namespacestd;9 TenTemplate <typename t> One classS A { - Private: -Vector<t>v; the Public: -S (initializer_list<t>l): V (L) - { -cout <<"constructed with a"<< l.size () <<"-element lists"<<Endl; + } - voidAppend (initializer_list<t>l) + { A V.insert (V.end (), L.begin (), L.end ()); at } - voidappend (t t) - { - V.push_back (t); - } - voidprint () in { -TypeName Vector<t>::iterator begin =V.begin (); to while(begin!=v.end ()) + { -cout << *begin++ <<Endl; the } * } $ };Panax Notoginseng - #endif //s_h_included
Look at the code of the call:
1#include <iostream>2#include"S.h"3 4 using namespacestd;5 6 intMain ()7 {8s<int> s{Ten};9S.append (1);TenS.append ({2,3,4,6,9}); Onecout <<"begin to print ()"<<Endl; A s.print (); - return 0; -}
The final print results are as follows:
Don't forget that the header file is #include <initializer_list>
C + + Initializer_list