一个仿Java类封装的std::list封装类(二)

2014-11-24 11:47:21 · 作者: · 浏览: 20
rayListIterator it = m_list->begin();
while( it != m_list->end() )
{
if( t == *it )
return it;
else
++it;
}
return m_list->end();
}
//查找t在列表中的索引
int indexOf(T t)
{
ArrayListIterator it = m_list->begin();
int index = 0;
while( it != m_list->end() )
{
if( t == *it )
return index;
++it ;
++index;
}
return -1;
}
//从末端起 查找t在列表中的索引
int lastIndexOf(T t)
{
ArrayListIterator it = m_list->end();
int index = count();
do
{
--it;
--index;
if( t == *it )
return index;
} while ( it != m_list->begin() ) ;
return -1;
}
//把列表导出为数组
T* toArray(T* array = NULL)
{
int cnt = count();
if( cnt == 0 )
return NULL;
if( array == NULL)
array = new T[cnt];
int index = 0;
ArrayListIterator it = m_list->begin();
while ( it != m_list->end() )
{
array[index] = *it;
++index;
++it;
}
return array;
}
//从数组里导到n个元素
void fromArray(T* array, int n)
{
for(int i=0;i
{
add(array[i]);
}
}
void sort( /* _Pr3 _Pred */ )
{
//未实现
}
//返回容器元素总个数
int count()
{
if( m_list->empty() )
return 0;
return m_list->size();
}
//复制一份当前实例的副本
ArrayList* clone()
{
//m_list->insert( .... )
ArrayList* array = new ArrayList();
T* elements = this->toArray();
int cnt = this->count();
array->fromArray(elements, cnt);
delete elements;
return array;
}
//获取m_list实例,由外部程序直接操作
std::list* getStdList()
{
return m_list;
}
private:
//unsigned int overflow
std::list* m_list;
};
#endif
Test01.cpp (VS2010下编译通过)
[cpp]
#include "stdafx.h"
#include "ArrayList.h"
int _tmain(int argc, _TCHAR* argv[])
{
ArrayList* array = new ArrayList();
for(int i=0;i<10;i++)
{
array->add( i );
}
array->add(2, 2);
array->addAt(100, 10000); www.2cto.com
printf("indexOf(2)=%d \n\r", array->indexOf(2));
printf("lastIndexOf(2)=%d \n\r", array->lastIndexOf(2));
//array->removeEx(2);
//array->removeAll();
ArrayList* array2 = array->clone();
for( int i=0;icount();i++)
{
printf("get(%d)=%d \n\r", i, array->get(i));
}
getchar();
return 0;
}