文章目录速览
- 1、使用C++泛型编程实现类似于vector的容器类ArrContainer
1、使用C++泛型编程实现类似于vector的容器类ArrContainer
直接上代码:可作读者参考
#pragma once
#include <exception>
template<typename T>
class ArrContainer
{
private:T* m_data; //存放数据int m_iCap; //容器的容量int m_iLen; //容器中元素的数量T* m_pHead; //头指针T* m_pRear; //尾部指针
public:ArrContainer() {m_iCap = 100;m_data = new T[m_iCap];m_iLen = 0;m_pHead = m_pRear = nullptr;}ArrContainer(int iLen){if (iLen < 0){m_data = nullptr;m_pHead = nullptr;m_pRear = nullptr;m_iLen = 0;m_iCap = 0;}m_iLen = iLen;}ArrContainer(T* data, int iLen){//step01: Judge the parameters whether are illegalif (nullptr == data || iLen <= 0){m_data = nullptr;m_pHead = nullptr;m_pRear = nullptr;m_iCap = 0;m_iLen = 0;return;}//step02: Allocate memory for datam_iCap = iLen + 100;m_iLen = iLen;m_data = new T[m_iCap];//step03: Copy datafor (int i = 0; i < m_iLen; ++i){m_data[i] = data[i];}m_pHead = &m_data[0];m_pRear = &m_data[m_iLen - 1];}~ArrContainer(){if (m_data != nullptr){delete[] m_data;m_data = nullptr;}}
public:bool push_back(const T& elem){if (m_iLen < m_iCap){m_data[m_iLen - 1] = elem;}m_pRear++;}T& operator[](int index){if (index < 0 || index >= m_iLen){exit(-1);}return m_data[index];}int size(){return m_iLen;}int capacity(){return m_iCap;}bool resize(int iLenNew){return false;}// 逆序算法bool reverse(){T tmp;while (m_pHead < m_pRear){tmp = *m_pHead;*m_pHead = *m_pRear;*m_pRear = tmp;m_pHead++;m_pRear--;}m_pHead = &m_data[0];m_pRear = &m_data[m_iLen - 1];return true;}
};