C/C++ 规定,数组一旦定义后,它的长度就不能改变了;换句话说,数组容量不能动态地增大或者减小。这样的数组称为静态数组(Static array)。静态数组有时候会给编码代码不便,我们可以通过自定义的 Array 类来实现动态数组(Dynamic array)。所谓动态数组,是指数组容量能够在使用的过程中随时增大或减小。
动态数组的完整实现代码如下:
复制代码
运行结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96#include <iostream> #include <cstring> #include <cstdlib> using namespace std; template<typename T, int N> class Array{ public: Array(); ~Array(); public: T & operator[](int i); //重载下标运算符[] int length() const { return m_length; } //获取数组长度 bool capacity(int n); //改变数组容量 private: int m_length; //数组的当前长度 int m_capacity; //当前内存的容量(能容乃的元素的个数) T *m_p; //指向数组内存的指针 }; template<typename T, int N> Array<T, N>::Array(){ m_p = new T[N]; m_capacity = m_length = N; } template<typename T, int N> Array<T, N>::~Array(){ delete[] m_p; } template<typename T, int N> T & Array<T, N>::operator[](int i){ if(i<0 || i>=m_length){ cout<<"Exception: Array index out of bounds!"<<endl; } return m_p[i]; } template<typename T, int N> bool Array<T, N>::capacity(int n){ if(n > 0){ //增大数组 int len = m_length + n; //增大后的数组长度 if(len <= m_capacity){ //现有内存足以容纳增大后的数组 m_length = len; return true; }else{ //现有内存不能容纳增大后的数组 T *pTemp = new T[m_length + 2 * n * sizeof(T)]; //增加的内存足以容纳 2*n 个元素 if(pTemp == NULL){ //内存分配失败 cout<<"Exception: Failed to allocate memory!"<<endl; return false; }else{ //内存分配成功 memcpy( pTemp, m_p, m_length*sizeof(T) ); delete[] m_p; m_p = pTemp; m_capacity = m_length = len; } } }else{ //收缩数组 int len = m_length - abs(n); //收缩后的数组长度 if(len < 0){ cout<<"Exception: Array length is too small!"<<endl; return false; }else{ m_length = len; return true; } } } int main(){ Array<int, 5> arr; //为数组元素赋值 for(int i=0, len=arr.length(); i<len; i++){ arr[i] = 2*i; } //第一次打印数组 for(int i=0, len=arr.length(); i<len; i++){ cout<<arr[i]<<" "; } cout<<endl; //扩大容量并为增加的元素赋值 arr.capacity(8); for(int i=5, len=arr.length(); i<len; i++){ arr[i] = 2*i; } //第二次打印数组 for(int i=0, len=arr.length(); i<len; i++){ cout<<arr[i]<<" "; } cout<<endl; //收缩容量 arr.capacity(-4); //第三次打印数组 for(int i=0, len=arr.length(); i<len; i++){ cout<<arr[i]<<" "; } cout<<endl; return 0; }
0 2 4 6 8
0 2 4 6 8 10 12 14 16 18 20 22 24
0 2 4 6 8 10 12 14 16
Array 是一个类模板,它有一个类型参数T
和一个非类型参数N
,T 指明了数组元素的类型,N 指明了数组长度。
capacity() 成员函数是 Array 类的关键,它使得数组容量可以动态地增加或者减小。传递给它一个正数时,数组容量增大;传递给它一个负数时,数组容量减小。
之所以能通过[ ]
来访问数组元素,是因为在 Array 类中以成员函数的形式重载了[ ]
运算符,并且返回值是数组元素的引用。如果直接返回数组元素的值,那么将无法给数组元素赋值。
最后
以上就是凶狠蜜粉最近收集整理的关于C++中定义动态数组的全部内容,更多相关C++中定义动态数组内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复