CS253: Software Development with C++

Spring 2018

Initializer Lists

See this page as a slide show

CS253 Initializer Lists

Initialization

Consider this code:

    vector<int> v = {11,22,33,44,55};

initializer_list

The name

Why is the name so god-awful long?

Standalone

Since an initializer_list has iterators, .begin(), and .end(), we can use it in a for loop:

for (auto v : {11,22,33,44,55})
    cout << v << ' ';
11 22 33 44 55 

or, more explicitly:

auto il = {11,22,33,44,55};
auto it = il.begin() + 3;
cout << *it << '\n';
44

or, even:

auto il = {11,22,33,44,55};
cout << *(il.begin()+3) << '\n';
44

Interaction with standard containers

So, how does this work?

unordered_set<int> us = {345,678,901,234,567,890};
for (auto v : us)
    cout << v << ' ';
890 567 234 901 678 345 

Constructor using initializer_list

The ctor must be this:

    unordered_set(const initializer_list<value_type> &);
    unordered_set<value_type> &operator=(const initializer_list<value_type> &)

Not Free

Example

class Hundred {
    int data[100];
  public:
    int &operator[](int n) { return data[n]; }
};

Hundred h;
h[1] = 123;
h[4] = 456;
cout << h[1]+h[4] << '\n';
579

Example that fails

class Hundred {
    int data[100];
  public:
    int &operator[](int n) { return data[n]; }
};

Hundred h = {11,22,33,44,55};
cout << h[1]+h[4] << '\n';
c.cc: In function 'int main()':
c.cc:7:28: error: could not convert '{11, 22, 33, 44, 55}' from 
   '<brace-enclosed initializer list>' to 'main()::Hundred'

Example

class Hundred {
    int data[100];
  public:
    Hundred(const initializer_list<int> &il) {
        copy(il.begin(), il.end(), data);
    }
    int &operator[](int n) { return data[n]; }
};

Hundred h = {11,22,33,44,55};
cout << h[1]+h[4] << '\n';
77

Example

class Hundred {
    int data[100];
  public:
    Hundred(const initializer_list<int> &il) {
        copy(il.begin(), il.end(), data);
    }
    int &operator[](int n) { return data[n]; }
};

Hundred h = {11,22,33,44,55};
cout << h[1]+h[4] << '\n';
h = {6,7,8,9};
cout << h[2] << '\n';
77
8

How did that work?

Example

class Hundred {
    int data[100];
  public:
    Hundred(const initializer_list<int> &il) {
        *this = il;
    }
    Hundred &operator=(const initializer_list<int> &il) {
        copy(il.begin(), il.end(), data);
        return *this;
    }
    int &operator[](int n) { return data[n]; }
};

Hundred h = {11,22,33,44,55};
cout << h[1]+h[4] << '\n';
h = {6,7,8,9};
cout << h[2] << '\n';
77
8

That’s better.

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-19T12:21

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building