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';
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access