Initializer lists in C++

Initializer lists, or if you prefer, initialiser lists, are a great addition of C++ 11, which allows you to 1) initialize your list-like classes and 2) uniform the initialisation of such objects comparing to what you can do with the built-in types.

Let us demonstrate it on the following example, which uses a simple array of integers:

#include <iostream>

int main() {
    int a[] = {1, 3, 5, 7};

    for (auto x : a)
        std::cout << x << "\n";
}

You could not easily change int[] to std::vector<int> earlier, as the compiler would not accept such initializing values.

Since C++ 11, you can:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v {1, 3, 5, 7};

    for (auto x : v)
        std::cout << x << "\n";
}

Alternatively, you can add the = sign:

std::vector<int> v = {1, 3, 5, 7};

Initializer lists can be also used in user-defined types. All you need is to add a constructor that accepts std::initializer_list. This is demonstrated in the next example, where a wrapper is created around the standard vector.

#include <iostream>
#include <initializer_list>
#include <vector>

struct data {
    std::vector<int> v;
    data(std::initializer_list<int> lst) : v(lst) {}
};

int main() {
    data a {1, 3, 5, 7};
    // data a = {1, 3, 5, 7};

    for (auto x : a.v)
        std::cout << x << "\n";
}

The only constructor here simply fills the v member with the values from the initializer list.

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code