vector
ttlb 2003-09-21 03:55:55 数据结构课上讲了顺序表,我觉得跟标准库里的vector差不多,就自己做了一个vector,当然功能还很少,和标准vector差得远。希望大家能帮我看看,还有什么能改进的地方?哪方面的意见都行。多谢啦。
// Copyright: ttlb(Tang Tao) 2003
// Version: 1.0
// This program simulates the Standard Template Library vector
// As an exercise of Data Structure
#ifndef _TTLB_VECTOR_H
#define _TTLB_VECTOR_H
#include <cassert>
#include <memory>
namespace ttlb
{
template <typename T>
class vector
{
public:
explicit vector(int iLength = 1000)
: m_iSize(0), m_iLength(iLength)
{
if (0 == m_iLength)
m_ptArr = 0;
else
m_ptArr = new T[m_iLength];
}
explicit vector(T *const ptBegin, T *const ptEnd)
: m_iSize(0), m_iLength(1000)
{
if (0 == m_iLength)
m_ptArr = 0;
else
m_ptArr = new T[m_iLength];
for (T *ptIter = ptBegin; ptIter != ptEnd; ++ptIter)
{
push_back(*ptIter);
}
}
explicit vector(const vector &cVSrc)
{
m_iSize = cVSrc.m_iSize;
m_iLength = cVSrc.m_iLength;
m_ptArr = new T[cVSrc.m_iLength];
memcpy(m_ptArr, dVSrc.m_ptArr, sizeof(T) * m_iSize);
}
virtual ~vector()
{
delete[] m_ptArr;
}
int size() const
{ // Size of the vector
return m_iSize;
}
void push_back(const T &tSrc)
{ // Push an element at the back
if (is_full())
resize(2 * m_iLength);
m_ptArr[m_iSize] = tSrc;
++m_iSize;
}
T pop_back()
{ // Pop an element at the back
assert(!is_empty());
return m_ptArr[--m_iSize];
}
void resize(int iNewLength)
{ // Resize the vector to the specified size
assert(iNewLength >= m_iSize);
m_iLength = iNewLength;
T *ptNewArr = new T[m_iLength];
memcpy(ptNewArr, m_ptArr, sizeof(T) * m_iSize);
delete m_ptArr;
m_ptArr = ptNewArr;
}
bool is_empty() const
{ // Is the vector empty
return 0 == m_iSize ? true : false;
}
bool is_full() const
{ // Is the vector full
return m_iSize == m_iLength ? true : false;
}
T* const begin() const
{ // The first element
return m_ptArr;
}
T* const end() const
{ // The element after the last
return m_ptArr + m_iSize;
}
T& operator[] (int iNum)
{ // Pick an element by its index
assert(iNum < m_iSize);
return m_ptArr[iNum];
}
static class Iterator
{ // vector Iterator
public:
Iterator(T *ptVal)
: m_ptVal(ptVal)
{
}
Iterator& operator++ ()
{
++m_ptVal;
return *this;
}
Iterator operator++ (int)
{
Iterator iter = m_ptVal++;
return iter;
}
bool operator== (Iterator iter) const
{
return iter.m_ptVal == m_ptVal;
}
bool operator!= (Iterator iter) const
{
return iter.m_ptVal != m_ptVal;
}
T operator *() const
{ // Convert Iterator to T*
return *m_ptVal;
}
private:
T *m_ptVal; // Pointing to one element of the vector
};
private:
int m_iSize; // Number of elements
T *m_ptArr; // An array storing the elements
int m_iLength; // Max length
};
}
#endif // _TTLB_VECTOR_H