4

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.

1
  • 2
    Thoroughly confused. Post the declarations for Class and Cell Commented Nov 24, 2010 at 13:40

2 Answers 2

3

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) !
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I didn't know I could ommit the type. You say its highly ineffective. How am I supposed to initialize the array then?
@problemofficer: I guess it's fine as long as Cell is cheap to copy
1

: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)))

Comments

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.