O'Reilly logo

C++ Primer Plus by Stephen Prata

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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';

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required