#ifndef T_VECTOR_H
#define T_VECTOR_H
/*
** 这个类适合存储大量数据,并支持随机访问
*/
#include <cassert>
#include <vector>
template<class T> class tvector
{
public:
typedef unsigned int size_type;
public:
tvector(size_type initSize = 1000, size_type increaseSize = 1000);
virtual ~tvector(void);
void push_back(const T &data);
T& operator[] (size_type index);
const T& operator[] (size_type index) const;
size_type size() const { return m_dataSize; }
private:
std::vector<T*> m_dataBlocks;
size_type m_initSize;
size_type m_increaseSize;
size_type m_capacity;
size_type m_dataSize;
size_type m_currentBlockID;
size_type m_nextDataID;
};
template<class T> tvector<T>::tvector(size_type initSize, size_type increaseSize)
{
m_initSize = initSize;
m_increaseSize = increaseSize;
T *firstBlock = new T[m_initSize];
assert(firstBlock != NULL);
memset(firstBlock, sizeof(T) * initSize, 0);
m_dataBlocks.push_back(firstBlock);
m_capacity = m_initSize;
m_dataSize = 0;
m_currentBlockID = 0;
m_nextDataID = 0;
}
template<class T> tvector<T>::~tvector()
{
for(std::vector<T*>::iterator it = m_dataBlocks.begin(); it != m_dataBlocks.end(); it++)
{
delete[] *it;
}
}
template<class T> void tvector<T>::push_back(const T &data)
{
if(m_capacity)
{
m_dataBlocks[m_currentBlockID][m_nextDataID++] = data;
m_capacity--;
}
else
{
T *block = new T[m_increaseSize];
assert(block != NULL);
memset(block, sizeof(T) * m_increaseSize, 0);
block[0] = data;
m_dataBlocks.push_back(block);
m_currentBlockID++;
m_nextDataID = 1;
m_capacity = m_increaseSize - 1;
}
m_dataSize++;
}
template<class T> T& tvector<T>::operator[](size_type index)
{
if(index < m_initSize) return m_dataBlocks[0][index];
else
{
size_type blockID = (index - m_initSize) / m_increaseSize + 1;
size_type dataID = (index - m_initSize) % m_increaseSize;
return m_dataBlocks[blockID][dataID];
}
}
template<class T> const T& tvector<T>::operator[](size_type index) const
{
if(index < m_initSize) return m_dataBlocks[0][index];
else
{
size_type blockID = (index - m_initSize) / m_increaseSize + 1;
size_type dataID = (index - m_initSize) % m_increaseSize;
return m_dataBlocks[blockID][dataID];
}
}
#endif
|