1 #pragma once 2 template<class T> 3 class CMyVector{ 4 private: 5 int m_nLenth;//长度 6 int m_nCount;//元素个数 7 T* m_pVec;//指针 8 public: 9 CMyVector(int nCount = 0, T tValue = 0){ 10 m_nCount = nCount; 11 m_nLenth = nCount; 12 if (nCount){ 13 m_pVec = new T[nCount]; 14 if (!m_pVec) 15 return; 16 for (UINT i = 0; i < nCount; i++){ 17 m_pVec[i] = tValue; 18 } 19 } 20 } 21 ~CMyVector(); 22 bool IsEmpty(){ 23 return !m_nCount; 24 } 25 bool IsFull(int nInsertCount = 1){ 26 return m_nCount + nInsertCount > m_nLenth; 27 } 28 bool Push_back(T tValue){ 29 if (IsFull()){ 30 Resize(); 31 } 32 m_pVec[m_nCount++] = tValue; 33 } 34 bool Resize(int nNum = 0){ 35 m_nLenth += nNum; 36 if (nNum){ 37 m_nLenth += nNum; 38 } 39 else{ 40 m_nLenth = m_nLenth * 2 + 1; 41 } 42 T* p = new T[m_nLenth]; 43 if (!p){ 44 //失败 45 } 46 47 ZeroMemory(p, sizeof(T)*m_nLenth); 48 memcpy_s(p, sizeof(T)*m_nCount, m_pVec, 49 sizeof(T)*m_nCount); 50 delete[] m_pVec; 51 m_pVec = p; 52 } 53 bool Pop_back(T &tValue){ 54 if (IsEmpty()){ 55 return false; 56 } 57 m_nCount--; 58 tValue = m_pVec[m_nCount];//可修改返回值 59 return true; 60 } 61 T operator[](int nIndex){ 62 if (nIndex > m_nCount - 1){ 63 //error 64 return 0; 65 } 66 return m_pVec[nIndex]; 67 } 68 bool Insert(int nPos, int nCount, T elem){ 69 if (nPos > m_nCount){ 70 71 } 72 if(IsFull(nCount)){ 73 Resize(); 74 } 75 for (UINT i = 0; i < m_nCount - nPos + 1; i++){ 76 m_pVec[nCount + m_nCount - 1 - i] = m_pVec[m_nCount - 1 - i]; 77 } 78 for (UINT i = 0; i < nCount; i++){ 79 m_pVec[nPos + i] = elem; 80 } 81 } 82 bool Insert(int nPos, T* begin, T* end){ 83 int nCount = (end - begin) / sizeof(T)+1; 84 if (nPos > m_nCount){ 85 86 } 87 if (IsFull(nCount)){ 88 Resize(); 89 } 90 for (UINT i = 0; i < m_nCount - nPos + 1; i++){ 91 m_pVec[m_nCount + nPos - 1 - i] = m_pVec[m_nCount - 1 - i]; 92 } 93 for (UINT i = 0; i < nCount; i++){ 94 m_pVec[nPos + i] = *begin; 95 begin++; 96 } 97 } 98 T& At(int nIndex){ 99 if (nIndex > m_nCount - 1){ 100 //error 101 } 102 return m_pVec[nIndex];//可修改值 103 } 104 };
实现自己的vector(简单模版)
让数据变得更安全!