简体   繁体   中英

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!

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM