首页 > 代码库 > 向量的插入与删除:

向量的插入与删除:

定义一个向量(vector)模板类,实现向量的初始化、插入、删除操作:

  1 #include "stdafx.h"
  2 #include <iostream>
  3 using namespace std;
  4 #define default_capacity 3
  5 template <typename T>
  6 vector class
  7 {
  8 private:
  9     int size;
 10     int capacity;
 11     T* elem;
 12 public:
 13     vector();
 14     void expand();
 15     void shrink();
 16     void insert(T &e,int i);
 17     void remove(int i);
 18     void print();
 19     T & operator[](int r);  //重载下标操作符,可以类似于数组形式引用各元素
 20     int getsize();
 21 };
 22 template <typename T>
 23 vector <T>::vector()
 24 {
 25     capacity = default_capacity;
 26     elem = new T[capacity];
 27     size = 0;
 28 }
 29 
 30 template <typename T>
 31 void vector<T>::expand()
 32 {
 33     if (size < capacity) return;    //规模小于容量
 34     T* oldelem = elem;
 35     elem = new T[capacity <<=1];
 36     for (int i = 0;i < size;i++)
 37         elem[i] = oldelem[i];
 38     delete[] oldelem;
 39 }
 40 
 41 template <typename T>
 42 void vector<T>::shrink()
 43 {
 44     if (capacity < default_capacity)
 45     {
 46         return;
 47     }//容量小于初始容量
 48     if ((size * 4) <= capacity)
 49     {
 50         T *oldelem = elem;
 51         elem = new T[capacity >>= 1];
 52         for (int i = 0;i < size;i++)
 53             elem[i] = oldelem[i];
 54         delete[]oldelem;
 55     }
 56 }
 57 
 58 template <typename T>
 59 void vector<T>::insert(T&e,int i)
 60 {
 61     expand();
 62     for (int j = size;j > r;j++)
 63     {
 64         elem[i] = elem[i - 1];
 65     }
 66     elem[i] = e;
 67     size++;
 68 }
 69 
 70 template <typename T>
 71 void vector<T>::remove(int i)
 72 {
 73     int j;
 74     T e = elem[i];
 75     for (j = i + 1;j < size;j++)
 76     {
 77         elem[j - 1] = elem[j];
 78     }
 79     size--;
 80     shrink();
 81     return e;
 82 }
 83 
 84 template <typename T>
 85 void vector<T>::print()
 86 {
 87     int i;
 88     for (i = 0;i < size;i++)
 89         cout << elem[i] << endl;
 90     cout << endl;
 91 }
 92 
 93 template <typenmae T>
 94 T & vector<T>::operator[](int r)
 95 {
 96     return elem[r];
 97 }
 98 
 99 template <typename T>
100 int vector<T>::getsize
101 {
102     return size;
103 }

 

向量的插入与删除: