C + + Initializer_list

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.