Question to structs and Memberinitialization

Hi everyone. I have read a codesnipet in a textbook, but i cannot imagine what it is doing.

What does that mean:

vector<Day> day {32};
32 elements of days?

vector<Month> month {12};
12 elements of months?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const int not_a_reading = –7777;
const int not_a_month = –1;

struct Day {
   vector<double> hour {vector<double>(24,not_a_reading)}; // long winded
   // vector<double> hour(24,not_a_reading); // better
};

struct Month {              // a month of temperature readings
   int month {not_a_month}; // [0:11] January is 0
   vector<Day> day {32};    // [1:31] one vector of readings per day
};

struct Year {                // a year of temperature readings, organized by month
   int year;                 // positive == A.D.
   vector<Month> month {12}; // [0:11] January is 0
};
Last edited on
The std::vector has many constructors:
http://www.cplusplus.com/reference/vector/vector/vector/
At first glance three of them look possible candidates:
(2) fill constructor
Constructs a container with n elements. Each element is a copy of val (if provided).
(4) copy constructor (and copying with allocator)
Constructs a container with a copy of each of the elements in x, in the same order.
(5) move constructor (and moving with allocator)
Constructs a container that acquires the elements of x.
If alloc is specified and is different from x's allocator, the elements are moved. Otherwise, no elements are constructed (their ownership is directly transferred).
x is left in an unspecified but valid state.
(6) initializer list constructor
Constructs a container with a copy of each of the elements in il, in the same order.

The question is now, whether vector<Day> day {32}; does use
1
2
3
vector (size_type n);
// or
vector (initializer_list<Day> il);

Can we test that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <vector>

struct Day {
  std::vector<double> hour {std::vector<double>(24,-7777)};
};

int main()
{
  std::vector<Day> day {32};
  std::cout << day.size() << '\n';
  std::cout << day[0].hour.size() << '\n';
  std::cout << day[0].hour[0] << '\n';
}

32
24
-7777

Ok:
* The std::vector<Day> day {32}; calls the fill constructor that creates 32 Days with default constructors.
* The vector<double>(24,not_a_reading) calls the fill too, to create 24 doubles and initialize each of them with -7777.

The vector<double> hour { temporary_unnamed_vector_object }; is optimized out, rather than moved or copied.
Thanks for the link to the cpp-reference page. I now understand the code snipet :-)
Topic archived. No new replies allowed.