Reputation: 27
Well, what I'm trying to do is to push back an object of the class I called Block
onto different vectors that keep Block
elements and are saved in a vector themselves.
std::vector<std::vector<Block>> mapvec;
mapvec[xcnt].push_back(new Block(xcnt,ycnt));
This is my progress until now.
error C2664: 'std::vector<_Ty>::push_back': convetion of the parameter 'Block *' in 'const Block &' not possible
(translated from German)
What should I do? Is there any other way to do what I want? Without using arrays?
Upvotes: 2
Views: 327
Reputation: 7919
You should :
mapvec[xcnt].push_back(Block(xcnt,ycnt));
Because you are holding instances of Block's, not their pointers
Upvotes: 0
Reputation: 1690
new
returns a pointer to a dynamically allocated object. This is not what you want to do here. Usually you want to pass a temporary (or already existing) object to push_back
and it will insert a copy into the memory.
So, simply get rid of new
. Like so:
std::vector<std::vector<Block>> mapvec;
mapvec[xcnt].push_back(Block(xcnt,ycnt));
This will make a temporary Block
-object and insert a copy into the vector.
If you want to use new
you need to store pointers in the vector, not Block
-objects. The safest way to do this is to use smart pointers:
std::vector<std::vector<std::unique_ptr<Block>>> mapvec;
mapvec[xcnt].push_back(std::unique_ptr<Block>(new Block(xcnt, ycnt)));
That way, the memory allocated with new
will be freed using delete
as soon as you remove the item from the vector or the vector gets destroyed.
Upvotes: 2
Reputation: 5988
new Block(xcnt,ycnt)
gives you Block*
pointing to the newly allocated Block
. And your vector expects Block
not Block*
Change it to
mapvec[xcnt].push_back(Block(xcnt,ycnt));
This will copy your Block
in to the vector so Block
class should have an accessible copy constructor.
Upvotes: 1
Reputation: 2019
Define your mapvec
as
std::vector<std::vector<Block*>> mapvec;
instead?
Upvotes: 1