向量的(查、增、删、改)

时间:2022-09-21 22:44:03
  1 #include "stdafx.h"
2 #include <iostream>
3 using namespace std;
4 template <typename T>
5 #define DEFAULT_CAPACITY 3
6 class vector
7 {
8 private:
9 int size;
10 int capacity;
11 T* elem; //定义数据区
12 public:
13 vector(); //构造函数
14 void insert(T &e, int i);
15 void expand(); //扩容
16 void shrink(); //缩容
17 T remove(int i); //删除
18 void print();
19 T &operator[] (int r); //重载下标操作符,类似于数组形式引用各元素
20 int getsize(); //获取当前元素总数
21 };
22
23 template <typename T>
24 vector<T>::vector()
25 {
26 capacity = DEFAUL_CAPACITY 3
27 elem = new T[capacity];
28 size = 0;
29 }
30
31 template <typename T>
32 void Vector<T>::insert(T &e, int i)
33 {
34 int j;
35 expand(); //若有必要,扩容
36 for (j = size; j>i; j++)
37 {
38 elem[j] = elem[j - 1];
39 }
40 elem[i] = e;
41 size++;
42 }
43
44 template <typename T>
45 void Vector<T>::expand()
46 {
47 if (size < capacity)
48 return;
49 cout << "expand" << endl;
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 template <typename T>
57 T Vector<T>::remove(int i)
58 {
59 int j;
60 T e;
61 e = elem[i];
62 for (j = i + 1; j<size; j++)
63 {
64 elem[j - 1] = elem[j];
65 }
66 size--;
67 shrink();
68 return e;
69 }
70 template <typename T>
71 void Vector<T>::shrink()
72 {
73 if (capacity < DEFAULT_CAPACITY)
74 return;
75 if ((size * 4) <= capacity)
76 {
77 cout << "shrink" << endl;
78 T *oldElem = elem;
79 elem = new T[capacity >>= 1];
80 for (int i = 0; i<size; i++)
81 elem[i] = oldElem[i];
82 delete[] oldElem;
83 }
84 }
85
86 template <typename T>
87 void Vector<T>::print()
88 {
89 int i;
90 for (i = 0; i<size; i++)
91 cout << elem[i] << endl;
92 cout << endl;
93 }
94
95 template <typename T>
96 T & Vector<T>::operator[](int r)
97 {
98 return elem[r];
99 }
100
101 template <typename T>
102
103 int Vector<T>::getsize()
104 {
105 return size;
106 }