You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.5 KiB
C++

#ifndef OBJECTMANAGER_H
#define OBJECTMANAGER_H
#include <vector>
#include <algorithm>
using std::vector;
/* @brief 对象管理类 */
template <class T> class CObjectManager
{
public:
CObjectManager(void){}
~CObjectManager(void){}
/* @brief 获取对象个数 */
size_t GetCount();
/* @brief 获取索引为index的对象 */
T* GetObject(size_t index);
/* @brief 添加对象 */
void Add(T* object);
/* @brief 在指定位置插入对象 */
void Insert(size_t index, T* object);
/* @brief 删除对象 */
void Delete(size_t index );
void Delete(T* object);
void DeleteAll();
/* @brief 移除对象 */
void Remove(size_t index);
void Remove(T* object);
void RemoveAll();
protected:
vector<T *> m_objectArray; ///< 保存对象数组
};
template <class T> size_t CObjectManager<T>::GetCount()
{
return m_objectArray.size();
}
template <class T> T * CObjectManager<T>::GetObject(size_t index)
{
assert(index >= 0 && index < m_objectArray.size());
return m_objectArray[index];
}
template <class T> void CObjectManager<T>::Add(T* object)
{
assert(NULL != object);
m_objectArray.push_back(object);
}
template <class T> void CObjectManager<T>::Insert(size_t index, T* object)
{
assert(index >= 0 && index <= m_objectArray.size() && NULL != object);
vector<T*>::iterator pos = m_objectArray.begin() + index;
m_objectArray.insert(pos, object);
}
template <class T> void CObjectManager<T>::Delete(size_t index)
{
assert(index >= 0 && index < m_objectArray.size());
vector<T *>::iterator pos = m_objectArray.begin() + index;
delete (*pos);
m_objectArray.erase(pos);
}
template <class T> void CObjectManager<T>::Delete(T* object)
{
assert(NULL != object);
vector<T *>::iterator pos = std::find(m_objectArray.begin(), m_objectArray.end(), object);
if (m_objectArray.end() != pos)
delete (*pos);
m_objectArray.erase(pos);
}
template <class T> void CObjectManager<T>::DeleteAll()
{
for (size_t i = 0; i < m_objectArray.size(); ++i)
{
delete m_objectArray[i];
}
m_objectArray.clear();
}
template <class T> void CObjectManager<T>::Remove(size_t index)
{
assert(index >= 0 && index < m_objectArray.size());
vector<T *>::iterator pos = m_objectArray.begin() + index ;
m_objectArray.erase(pos);
}
template <class T> void CObjectManager<T>::Remove(T* object)
{
assert(NULL != object);
vector<T *>::iterator pos = std::find(m_objectArray.begin(), m_objectArray.end(), object);
if (m_objectArray.end() != pos)
m_objectArray.erase(pos);
}
template <class T> void CObjectManager<T>::RemoveAll()
{
m_objectArray.clear();
}
#endif