动态数组(int型、整型),可自动扩容
程序员文章站
2022-07-15 10:10:20
...
如果直接定义一个数组,数组初始化后的长度是固定的,存入的数据数量有限,无法扩容存入更多数据。
利用C++的抽象类可实现可扩容的动态数组。功能:
- add(int dat):向数组插入一个数据
- get(int index):按照索引(下标)获取数组中的数据
- size():得到数组的大小
- travel():把数组打印一遍
- remove(int index):按照索引(下标)删除数组中的数据
//可扩容的动态int型数组,例程:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int count = 1;
class List {
public:
virtual void add(int dat) = 0;
virtual int get(int index) = 0;
virtual int size() = 0;
virtual void travel() = 0;
virtual int remove(int index) = 0;
virtual ~List() {
}
;
};
class ArrayList: public List {
public:
ArrayList() {
len = 10;
arr_Size = 0;
this->arr = new int[len];
//printf("No.%d\tarr.addr=%p\n", count++, arr);
}
~ArrayList() {
//printf("No.%d\tarr.addr=%p\n", count++, arr);
delete[] arr;
}
void add(int dat) {
*(arr + arr_Size) = dat;
arr_Size++;
if (arr_Size >= len) {
arr_Expansion();
}
}
int size() {
return arr_Size;
}
void travel() {
int i = 0;
printf(
"============================================================================\n");
printf("arr_Size:%d\n", arr_Size);
for (; i < arr_Size; i++) {
printf("%d\t", *(arr + i));
if (i % 10 == 9) {
printf("\n");
}
}
printf("\n");
printf(
"============================================================================\n");
}
int get(int index) {
return *(arr + index);
}
int remove(int index) {//要加一个index在0~arr_Size之间的判断,不在就是越界,return -1
for (int i = index; i < arr_Size; i++) {
if(index == arr_Size){
*(arr+arr_Size)='\0';
}
*(arr+i)=*(arr+i+1);
}
arr_Size--;
printf("It is successful to remove!\n");
return 1;
}
private:
int len;
int arr_Size;
int* arr;
void arr_Expansion() {
int* arr1 = arr;
len += 10;
arr = new int[len];
for (int i = 0; i < len; i++) {
*(arr + i) = *(arr1 + i);
}
delete[] arr1;
printf("No.%d\tarr.addr=%p\n", count++, arr);
}
};
int main() {
ArrayList list;
for (int i = 1; i <= 35; i++) {
list.add(i);
}
list.travel();
int index;
printf("index:");
scanf("%d", &index);
printf("list[%d]=%d\n", index, list.get(index));
printf("index to remove:");
scanf("%d", &index);
list.remove(index);
list.travel();
}
运算结果(Eclipse):
推荐阅读