一个数组储存对象指针,如何改成用STL容器类储存?

发布时间:2019-08-06 23:49:23

一个数组储存对象指针,如何改成用STL容器类储存?

推荐回答

声明:vector<DisplayableObject*> m_vecDisplayableObject;

Create直接将new出来DisplayableObject*的对象push进去就是,

Destroy不用说了,

在UpdateAllObjects里面:

12345678910void BaseEngine::UpdateAllObjects( int iCurrentTime ){    m_iDrawableObjectsChanged = 0;    for (vector<DisplayableObject*>::iterator it=m_vecDisplayableObject.begin(), it!=m_vecDisplayableObject.end(), ++it)    {        it->DoUpdate(iCurrentTime);        if ( m_iDrawableObjectsChanged )            return; // Abort! Something changed in the array    }}

如果不需要判断m_iDrawableObjectsChanged是否退出,可以自己写个my_for_each的调用DoUpdate的算法:

123456789template<class _InIt,class _Fn1,class _Arg> inline    _Fn1 my_for_each(_InIt _First, _InIt _Last, _Fn1 _Func, _Arg _Right){       for (; _First != _Last; ++_First)        _Func(*_First, _Right);    return (_Func);}

最后在UpdateAllObjects里面执行算法就行了,代码会很简洁:

1234void BaseEngine::UpdateAllObjects( int iCurrentTime ){    my_for_each(m_vecDisplayableObject.begin(), m_vecDisplayableObject.end(), mem_fun1(&DisplayableObject::DoUpdate), iCurrentTime);}
以上问题属网友观点,不代表本站立场,仅供参考!