Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About initializing a vector in C++11

In Stroustrup's book, "Programming: Principles and Practices of Programming Using C++ (Second Edition)", the author creates a struct as follows:

const int not_a_reading = –7777;

struct Day {
vector<double> hour {vector<double>(24,not_a_reading)};
};
// As the author says: "That is, a Day has 24 hours, 
// each initialized to not_a_reading."

I know vector<double> hour{24, not_a_reading} won't do because it initializes a vector of two elements, 24 and -7777, which isn't the desired object.

But is there any reason why the author's initialization technique is superior to just doing:

vector<double> hour(24, not_a_reading)

(?)

like image 999
Aky Avatar asked Jun 11 '16 19:06

Aky


1 Answers

In the code above, the following is a class (struct) non static data member hour:

vector<double> hour {vector<double>(24,not_a_reading)};

It has a default member initializer: {vector<double>(24,not_a_reading)}

But is there any reason why the author's initialization technique is superior to just doing:

vector<double> hour(24, not_a_reading)

Yes, you would not be able to write the initializer of a class member that way. You need the curly braces in the class (struct) definition to make it an initializer or you could use the syntax: vector<double> hour = vector<double>(24,not_a_reading); which would mean the same thing.

#include <vector>

using namespace std;

int main()
{
    const int not_a_reading = -7777;

    struct Day {
        vector<double> hour{vector<double>(24,not_a_reading)}; // create a vector of doubles object with the constructor and then initialize hour with 24 doubles
        vector<double> hour2 = vector<double>(24,not_a_reading); // same as above
    };

    //struct Day2 {
    //  vector<double> hour(24,not_a_reading); // syntax error
    //};

    struct Day3 {
      vector<double> hour(int,int); // function declaration!
    };

    vector<double> other_hour(24,not_a_reading); // ok here
    vector<double> other_hour2(); // function declaration, most vexing parse!
    vector<double> another_hour{vector<double>(24,not_a_reading)}; // also ok here

    return 0;
}

A possible reason that vector<double> hour(24,not_a_reading); is not allowed to create an hour object is because under certain circumstances it could be confused with a function declaration. The so called most vexing parse.

like image 104
wally Avatar answered Sep 19 '22 07:09

wally