C++设计动态数组类 DynamicArray,可以实现增加,删除,插入,排序等功能
时间: 2023-08-16 10:07:03 浏览: 39
好的,以下是一个简单的 C++ DynamicArray 类的实现,包括增加、删除、插入、排序等功能:
```c++
#include <iostream>
#include <algorithm>
class DynamicArray {
private:
int* data;
int size;
int capacity;
public:
DynamicArray(int capacity = 10) {
this->capacity = capacity;
size = 0;
data = new int[capacity];
}
~DynamicArray() {
delete[] data;
}
void add(int val) {
if (size == capacity) {
capacity *= 2;
int* new_data = new int[capacity];
std::copy(data, data + size, new_data);
delete[] data;
data = new_data;
}
data[size++] = val;
}
void remove(int index) {
if (index < 0 || index >= size)
throw std::out_of_range("Index out of range!");
for (int i = index; i < size - 1; ++i)
data[i] = data[i + 1];
--size;
}
void insert(int index, int val) {
if (index < 0 || index > size)
throw std::out_of_range("Index out of range!");
if (size == capacity) {
capacity *= 2;
int* new_data = new int[capacity];
std::copy(data, data + size, new_data);
delete[] data;
data = new_data;
}
for (int i = size; i > index; --i)
data[i] = data[i - 1];
data[index] = val;
++size;
}
void sort() {
std::sort(data, data + size);
}
int getSize() const {
return size;
}
int getCapacity() const {
return capacity;
}
int& operator[](int index) {
if (index < 0 || index >= size)
throw std::out_of_range("Index out of range!");
return data[index];
}
const int& operator[](int index) const {
if (index < 0 || index >= size)
throw std::out_of_range("Index out of range!");
return data[index];
}
};
```
这个 DynamicArray 类支持动态增长,可以使用 add() 方法在末尾添加元素,remove() 方法删除指定索引的元素,insert() 方法在指定索引处插入元素,sort() 方法对所有元素进行排序。getSize() 和 getCapacity() 方法分别返回元素数量和数组容量。还重载了 [] 运算符,使得可以通过索引访问元素。