1

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!

2
  • 3
    Youre missing part of the error but more importantly the first version only "works" because it doesnt do what you think it does. Lookup Most Vexing Parse. The problem is your type doesnt have a default constructor and youre trying to create 20 default objects of that type. Commented Jun 26, 2017 at 20:24
  • Thanks . I missed adding the default constructor and couldn't figure that out from the error message. Commented Jun 26, 2017 at 20:30

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

0

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!

2 Comments

Hello, welcome to the site. Please read this markdown tutorial to learn how to format code in your answers.
Also, keep in mind the OP is asking for an explanation of the error as well as a solution, consider providing that too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.