Reputation: 1017
I have a struct as defined below
struct valindex {
int x;
int y;
valindex(int val, int index) : x(val), y(index) {}
};
I'm getting an error when trying to initialize a vector of this struct
vector<valindex> vals() // this works fine
vector<valindex> vals(20) // throws the error mentioned below when the size is specified
required from 'static _ForwardIterator std::__uninitialized_default_n_1<_TrivialValueType>::__uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = valindex*; _Size = long unsigned int; bool _TrivialValueType = false]'
Can someone explain the cause of this error and provide a solution?
Thanks!
Upvotes: 1
Views: 689
Reputation: 15
std::vector has another helpful constructor:
std::vector vals(999, {11, 55});
Vector vals will store 999 copies of valindex(11, 55). Welcome to c++11!
Upvotes: 0
Reputation: 206577
vector<valindex> vals();
works because it declares a function named vals
that takes no arguments and returns a vector<valindex>
. See https://en.wikipedia.org/wiki/Most_vexing_parse.
vector<valindex> vals(20);
does not work since it tries construct a vector
of valindex
and one of the requirements of creating such an object is that valindex
be default-constructible. Since valindex
is not default-constructible, that line cannot be compiled.
Upvotes: 3