(C++) Can't get deque insert() to work, what am I doing wrong?
I'm getting an error on the insert()
part here, and I dunno what I am doing wrong. I've tried different parameters and number of parameters but nothing seems开发者_Go百科 to work.
m_oGameObjectList
is a deque of IGameObjects (base class).
m_sPosition
is a struct with 3 ints (X, Y, Z).
gameObject
is the reference to an object derived from IGameObject
.
for (int i = 0; i < m_oGameObjectList.size(); i++)
{
if (gameObject.m_sPosition.Z > m_oGameObjectList[i].m_sPosition.Z)
{
m_oGameObjectList.insert(i, gameObject);
i = m_oGameObjectList.size();
}
}
insert
takes an iterator
. Use:
m_oGameObjectList.insert(m_oGameObjectList.begin() + i, gameObject);
You'll also need to use pointers in your deque
, right now you're slicing - inserting a copy of the IGameObject
part of gameObject
Your call to insert
should pass an iterator (not an integer index) into the deque. One way you can convert an integer index to a deque iterator is via:
my_deque_iterator iter = m_oGameObjectList.begin();
std::advance(m_oGameObjectList, i);
... though there are several other solutions that work equally well.
You can also use deque functions like push_back
and push_front
which just take the object you want to put at the front or back of the deque, respectively.
trying to insert an object derived from IGameObject into a deque<IGameObject> won't work as the deque is trying to store a copy of the object in the reference, not the reference itself.
Most of the time, if your trying to store an class hiearchy into a container, you do so by having the container of pointers to the base class.
精彩评论