Search code examples
c++vectorinitializationinitializer-list

Initializing vector with data not working - push_back() does work


I am trying to create a vector of typedefs. Whenever I try to initialize a vector with one of these typedefs, it gives a no instance of constructor error.

The typedef is defined as follows:

typedef palam::geometry::Pt2<uint16_t> CPoints;

and I am trying to initialize a vector like this:

CPoints point1(10, 15);
CPoints point2(15, 20);
std::vector<CPoints> points(point1, point2);

but that does not work. I am able to get around this issue by initializing the vector with a NULL value and then using the push_back() function, like this

CPoints point1(10, 15);
CPoints point2(15, 20);
std::vector<CPoints> points(NULL);
points.push_back(point1);
points.push_back(point2);

This work around seems a bit messy, and I am sure there must be a better way to go about this. Does anyone know why I am unable to directly initialize the vector using the typedefs?


Solution

  • This snippet:

    std::vector<CPoints> points(point1, point2);
    

    calls the vector constructor taking 2 arguments. If you want to initialize a vector with multiple elements, use {}, like this:

    std::vector<CPoints> points {point1, point2};
    

    This calls overload number 9, which takes an initializer list.