Sumit Das
Sumit Das

Reputation: 1017

Error in Initializing a vector of structures with a size

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

Answers (2)

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

R Sahu
R Sahu

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

Related Questions