1 of 9

Initializer Lists

CSE 232 - Dr. Josh Nahum

2 of 9

Reading:

Section 5.2.3

3 of 9

Table of contents

00

01

Streams

Copy

4 of 9

00

Streams

5 of 9

read Function

Two facts to remember:

  • is >> d is an expression that is true as long as the stream is not in an error state.
  • Streams can't be copied, but you can pass references (or pointers) to them to functions.

Vector read(istream & is) {

Vector v;

for (double d; is >> d; ) {

v.push_back(d);

}

return v;

}

6 of 9

01

Copy

7 of 9

Initializer-list Constructor

Vector::Vector(std::initializer_list<double> lst)

:elem{new double[lst.size()]}, sz{static_cast<int>(lst.size())} {

copy(lst.begin(), lst.end(), elem);

}

std::copy is a function from the <algorithm> library. It takes three arguments:

  1. An iterator to the first element in a container to be copied
  2. An iterator to one past the last element in a container to be copied
  3. An iterator to the first element in a container to be overwritten by the copy

An example without using untaught material follows.

8 of 9

Initializer-list Constructor

Vector::Vector(std::initializer_list<double> lst)

:elem{new double[list.size()]}, sz{static_cast<int>(lst.size())} {

for (int i{0}; i < sz; ++i) {

elem[i] = lst[i];

}

}

Unfortunately arrays (like elem) and std::initializer_lists (like lst) don't support the at method, so we have to use the less safe operator[].

9 of 9

Attribution

Dr. Joshua Nahum

www.nahum.us

EB 3504

Please ask questions via Piazza

© Michigan State University - CSE 232 - Introduction to Programming II

CREDITS: This presentation template was created by Slidesgo, and includes icons by Flaticon, and infographics & images by Freepik