C ++ Initializing a Vector Inside a Structure Definition

I read the principles of C ++ programming and practice and stumbled upon the following piece of code, which I think was not well explained.

struct Day {
    vector<double> hour{vector<double>(24,-777) };
};

What's going on here? I usually use this initializer when I need a vector of a certain length with default values:

vector<double> hour(24, -777);

However, this initialization method does not work inside the structure,

struct Day {
    vector<double> hour(24, -777);
};

Compilation Error Results

Error (active)      expected a type specifier   HelloWorld  d:\Visual Studio 2015\HelloWorld\HelloWorld\HelloWorld.cpp  11  
Error (active)      expected a type specifier   HelloWorld  d:\Visual Studio 2015\HelloWorld\HelloWorld\HelloWorld.cpp  11  
Error   C2059   syntax error: 'constant'    HelloWorld  d:\visual studio 2015\helloworld\helloworld\helloworld.cpp  11  

Look for an explanation behind the initializers.

I am using MS Visual Studio 2015

+4
source share
4 answers
vector<double>(24,-777)

This creates a temporary std::vectorwith 24 values -777.

hour , .

+3

Visual Studio 2015: http://rextester.com/WIS16088 , - ?

, , :

  1. , , , hours brace-init-list, a vector<int> http://en.cppreference.com/w/cpp/container/vector/vector 2 nd :

, hours, , 24 int -777, .

0

++ 11 initializer_list , :

struct Day {
    std::vector<double> hours = { 1.0, 2.0, 3.0 };
};

(, 24 -777.0) initializer_list - , , , auto ( static constexpr ). , 24u , size_t double , ( ):

struct Day {
    std::vector<double> hours = std::vector<double>(24u, -777.);
};

auto :

struct Day {
    static constexpr auto default_hours_size = 24u;
    std::vector<double> hours = std::vector<double>(default_hours_size, -777.);
};
0

. , :

struct Day {
    vector<double> hour = vector<double>(24,7);
};
-1
source

Source: https://habr.com/ru/post/1662401/


All Articles