Lesson 184 +10 XP

std::initializer_list

std::initializer_list

You already write braces all the time: std::vector<int> v = {1, 2, 3};. The braced list on the right is itself a type: std::initializer_list. And you can pass one directly to a function.

A function that takes a list

#include <initializer_list>
#include <iostream>

void printAll(std::initializer_list<int> nums) {
    for (int n : nums) {
        std::cout << n << " ";
    }
}

int main() {
    printAll({1, 2, 3});      // prints 1 2 3
    printAll({4, 5, 6, 7});   // prints 4 5 6 7
    return 0;
}

One signature, and the caller drops in any length of values. That is the whole idea: you do not pin down the size up front.

Where the braces show up in practice

  • Vector and map constructors, like std::vector<int> v = {1, 2, 3};, accept brace lists.
  • printAll({1, 2, 3}) fills the parameter with the braced values.
  • Your own functions can ask for "a pile of values" and not think about size at all.

The header

A container often pulls in the type for you, but if you write std::initializer_list yourself, include it:

#include <initializer_list>

TL;DR

  • std::initializer_list<int> is a list of ints written in braces.
  • A function parameter with that type accepts {1, 2, 3} or any other length.
  • Container constructors use it so that = { ... } works.
  • Include <initializer_list> when you use the type yourself.