Home > OS >  Creating a vector with n elements in a struct
Creating a vector with n elements in a struct

Time:11-11

If I just write this code:

std::vector<int> vec(24, 3);

It'll create a vector called vec with 24 elements all equal to 3. But if I have a struct:

struct Day
{
    std::vector<int> days(24, 3);
};

And try to do the exact same thing it doesn't work, why is this?

CodePudding user response:

Syntax would be:

struct Day
{
    vector<int> days = vector<int>(24, 3);
};

You cannot call constructor with () syntax there (to avoid vexing parse) (but can with {}or = /*...*/).

CodePudding user response:

struct Day
{
    std::vector<int> days(24, 3);
};

As already mentioned in the other answer, you can't call the constructor with (), as that syntax would trigger the most vexing parse.

In fact, days would be interpreted as the declaration of a member function Day::days(), returning a std::vector<int>, and taking two parameters. However, the type of these parameters is not specified, so you get a compile-time error.

It's interesting to note that you may think of calling the constructor using the uniform initialization syntax with curly braces {}:

struct Day
{
    std::vector<int> days{24, 3};  // Pay attention!
};

This code does compile; but it creates a wrong vector, not what you expected. In fact, it creates a vector containing the two integer numbers 24 and 3. This is because this syntax invokes the std::vector constructor taking an initializer list, not the (element count, element value) constructor overload you meant.

So, a valid option is to use the more verbose syntax:

struct Day
{
    std::vector<int> days = std::vector<int>(24, 3);
};
  • Related