Using initializer_list

You can use initializer_list objects in your code by including the initializer_list header file. The template class has begin() and end() members, and you can use them to access list elements. It also has a size() member that returns the number of elements. Listing 16.22 shows a simple example using initializer_list. It requires a compiler that supports this C++11 feature.

Listing 16.22. ilist.cpp

// ilist.cpp -- use initializer_list (C++11 feature)#include <iostream>#include <initializer_list>double sum(std::initializer_list<double> il);double average(const std::initializer_list<double> & ril);int main(){    using std::cout;    cout << "List 1: sum = " << sum({2,3,4})         <<", ave = " << average({2,3,4}) << '\n';

Get C++ Primer Plus now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.