ArrayList.h
[cpp]
/************************************************************************/
/* ArrayList */
/* 一个仿
Java类封装的std::list封装类(头文件包含函数实现体) */
/* author:Sinmax, date:2013-02-25 */
/************************************************************************/
#ifndef _ARRAY_LIST_H_
#define _ARRAY_LIST_H_
#include
using namespace std;
template
class ArrayList
{
public:
typedef typename std::list::iterator ArrayListIterator;
ArrayList()
: m_list(0)
{
m_list = new std::list();
};
~ArrayList()
{
m_list->clear();
delete m_list;
};
//添加一个元素(到末端)
void add(T t)
{
m_list->push_back(t);
}
//添加一个元素:在指定索引,指定索引大于列表长度,则添加到末端
void add(T t, int index )
{
if( index < 0 )
{
//ignore , not recommand m_list->push_front(t);
}
else if( index == 0 )
{
m_list->push_front(t);
}
else if( index < count() - 1 )
{
ArrayListIterator it = m_list->begin();
int n = 0;
while( n < index )
{
++it;
++n;
}
m_list->insert(it, t);
}
else
{
m_list->push_back(t);
}
}
//获取指定索引的元素
T get(int index)
{
int length = count();
if( index == 0 )
{
return m_list->front();
}
else if( index < length - 1 )
{
int n = 0;
ArrayListIterator it = m_list->begin();
while ( ++n <= index )
{
++it;
}
return *it;
}
else if( index == length - 1 )
{
return m_list->back();
}
return NULL;
}
//删除指定的元素(第一个找到)
void remove(T t)
{
ArrayListIterator it = indexOfIt(t);
if( it != m_list->end() )
{
m_list->erase(it);
}
}
//删除指定的元素(所有找到)
void removeEx(T t)
{
m_list->remove(t);
}
//删除指定索引的元素,并返回该索引的元素
T removeAt(int index)
{
if( index < 0 )
{
//ignore
return NULL;
}
int length = count();
T t = NULL;
if ( index >= length )
{
return NULL;
}
else if ( index == 0 )
{
t = m_list->front();
m_list->pop_front();
return t;
}
else if( index == length - 1 )
{
t = m_list->front();
m_list->pop_front();
return t;
}
else if( index < length )
{
ArrayListIterator it = m_list->begin();
while( --length > 0 )
{
++it;
}
t = *it;
m_list->erase(it);
return t;
}
return NULL;
}
//删除所有元素
void removeAll()
{
m_list->clear();
}
//查找等于t元素的迭代器
const ArrayListIterator indexOfIt(T t)
{
Ar