JeanC
JeanC

Reputation: 38

In struct initialization

Something baffles me about C++, I can write something like:

struct Test {
    double V[3];
}

without a problem, but when I try for e.g.:

struct Test {
    vector<double> V(3);
}

the compiler gives me an error. What is the difference between the above, I mean why can't the second one be compiled?

and, this one is even more baffling:

struct Test {
    std::vector<double> V[3];
}

The last example that at least in my mind should throw a compiler error is compiled without a problem by both GCC and Clang.

Upvotes: 1

Views: 88

Answers (4)

SirDarius
SirDarius

Reputation: 42969

What you want to do here is:

struct Test {
    vector<double> v;

    Test(): v(3) {}
};

which adds a constructor to your structure with an initialization list that explicitely invokes the vector's constructor with 3 as a parameter.

It is otherwise not possible to call a constructor in the context of declaring structure or class members (excepting initializer lists constructors with the specific C++11 syntax using curly braces).

More generally, fixed-size arrays should use the std::array class, as mentioned before.

Upvotes: 1

gexicide
gexicide

Reputation: 40118

Do not confuse initialization and declaration.

double V[3];

This declares an array of three doubles. No problem. No initialization.

vector<double> V(3);

This declares a vector and tries to initialize it by calling its constructor with 3 as argument. Initialization like this is not allowed here. With C++11 you can use initialization syntax with curly braces, this is allowed:

vector<double> V{3};

However, since vector has a constructor that takes an initializer_list<double>, this will be interpreted as calling that constructor, not the one that takes a size_t value (the one you want). It will initialize the vector with a single element (3.0). You could use V{0,0,0} for what you want, though this might get ugly once you need more than 3 values.

Your final example

std::vector<double> V[3];

simply declares an array of three vectors. No initialization. No problem.

Upvotes: 4

OmnipotentEntity
OmnipotentEntity

Reputation: 17131

It seems like you want a fixed length array stl type. std::vector isn't this. You're looking for std::array

You probably want std::array<double, 3>.

Please disregard if this isn't your intention.

Upvotes: 1

Sebastian Redl
Sebastian Redl

Reputation: 72063

Those are different things.

The first declares an array of three elements. The [3] is part of the type.

The second declares a vector, and then uses something that looks like initialization syntax, but isn't allowed in this particular context. The (3) is not part of the type. (Note that in C++11 or 14 you get in-class initializers that allow something similar.)

The third declares an array of three vectors. Compare the syntax to the first one: all that changes is that double is replaced by std::vector<double>.

Upvotes: 2

Related Questions