设计实现一个表示动态数组的类。实现数组中数据的增加,删除,输出功能
时间: 2024-03-07 11:47:14 浏览: 27
好的,我可以帮你设计实现一个动态数组类。这个类可以动态地调整数组的大小,同时支持数据的增加、删除和输出功能。下面是一个简单的示例代码:
```c++
#include <iostream>
using namespace std;
class DynamicArray {
private:
int* data; // 存储数组的指针
int size; // 数组的大小
int capacity; // 数组的容量
public:
// 构造函数
DynamicArray(int cap = 16) {
capacity = cap;
size = 0;
data = new int[capacity];
}
// 析构函数
~DynamicArray() {
delete[] data;
}
// 数组大小
int getSize() {
return size;
}
// 数组容量
int getCapacity() {
return capacity;
}
// 数组是否为空
bool isEmpty() {
return size == 0;
}
// 在数组末尾添加元素
void add(int e) {
if (size == capacity) {
resize(2 * capacity);
}
data[size++] = e;
}
// 在指定位置插入元素
void insert(int index, int e) {
if (index < 0 || index > size) {
throw out_of_range("Index out of range");
}
if (size == capacity) {
resize(2 * capacity);
}
for (int i = size - 1; i >= index; i--) {
data[i + 1] = data[i];
}
data[index] = e;
size++;
}
// 删除指定位置的元素
void remove(int index) {
if (index < 0 || index >= size) {
throw out_of_range("Index out of range");
}
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
if (size == capacity / 4 && capacity / 2 != 0) {
resize(capacity / 2);
}
}
// 获取指定位置的元素
int get(int index) {
if (index < 0 || index >= size) {
throw out_of_range("Index out of range");
}
return data[index];
}
// 修改指定位置的元素
void set(int index, int e) {
if (index < 0 || index >= size) {
throw out_of_range("Index out of range");
}
data[index] = e;
}
// 重载运算符[],方便数组访问
int& operator[](int index) {
if (index < 0 || index >= size) {
throw out_of_range("Index out of range");
}
return data[index];
}
// 扩容函数
void resize(int newCapacity) {
int* newData = new int[newCapacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
delete[] data;
data = newData;
capacity = newCapacity;
}
// 输出数组
void print() {
cout << "[";
for (int i = 0; i < size; i++) {
cout << data[i];
if (i != size - 1) {
cout << ", ";
}
}
cout << "]" << endl;
}
};
```
这个类可以通过以下方式使用:
```c++
int main() {
DynamicArray arr;
arr.add(1);
arr.add(2);
arr.add(3);
arr.insert(1, 4);
arr.remove(2);
arr.print();
return 0;
}
```
输出结果为:
```
[1, 4, 3]
```
希望能够帮到你!