problemofficer
problemofficer

Reputation: 435

Call non-default constructor for object in vector initialization

I want to initialize a vector in an initialization list of a constructor. The vector consists of objects with a parameterized constructor. What I have is:

Class::Class() : 
   raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80)))
{
...

How can I call Cell::Cell with two parameters in the above line? The obvious:

raster_(std::vector< std::vector<Cell(true,true)> > (60, std::vector<Cell(true,true)>(80)))

didn't work.

Upvotes: 4

Views: 1984

Answers (2)

icecrime
icecrime

Reputation: 76755

You should try :

Class::Class() : 
     raster_(60, std::vector<Cell>(80, Cell(true, true)))
{
    /* ... */
}

Note that I removed the useless std::vector<std::vector<Cell> > from the initializer. Also be aware that this could be highly ineffective depending on the cost of copying a Cell :

  • It creates an std::vector<Cell> by copying 80 times the provided value Cell(true, true)
  • It creates an std::vector<std::vector<Cell> > by copying 60 times the provided vector (which contains 80 elements itself) !

Upvotes: 3

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132994

:raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80, Cell(true, true))));

if raster_ is something that takes the vector. If raster_ itself is the vector then like this

:raster(60, std::vector<Cell>(80, Cell(true, true)))

Upvotes: 1

Related Questions