c++实现的一个MyArrayList
时间: 2024-02-24 11:59:27 浏览: 70
C#自建类实现集合接口IEnumerable, IEnumerator
4星 · 用户满意度95%
好的,下面是C++实现的一个MyArrayList,其中包含了常见的数组操作函数:
```c++
#include <iostream>
#include <stdexcept>
template <typename T>
class MyArrayList {
private:
T *data;
int size;
int capacity;
public:
MyArrayList(int capacity = 10) {
this->capacity = capacity;
data = new T[capacity];
size = 0;
}
~MyArrayList() {
delete[] data;
}
int getSize() const {
return size;
}
bool isEmpty() const {
return size == 0;
}
void add(int index, T e) {
if (index < 0 || index > size)
throw std::invalid_argument("Add failed. Index is invalid.");
if (size == capacity)
resize(2 * capacity);
for (int i = size - 1; i >= index; i--)
data[i + 1] = data[i];
data[index] = e;
size++;
}
void addLast(T e) {
add(size, e);
}
void addFirst(T e) {
add(0, e);
}
T get(int index) const {
if (index < 0 || index >= size)
throw std::invalid_argument("Get failed. Index is invalid.");
return data[index];
}
void set(int index, T e) {
if (index < 0 || index >= size)
throw std::invalid_argument("Set failed. Index is invalid.");
data[index] = e;
}
bool contains(T e) const {
for (int i = 0; i < size; i++) {
if (data[i] == e)
return true;
}
return false;
}
int find(T e) const {
for (int i = 0; i < size; i++) {
if (data[i] == e)
return i;
}
return -1;
}
T remove(int index) {
if (index < 0 || index >= size)
throw std::invalid_argument("Remove failed. Index is invalid.");
T ret = data[index];
for (int i = index + 1; i < size; i++)
data[i - 1] = data[i];
size--;
if (size == capacity / 4 && capacity / 2 != 0)
resize(capacity / 2);
return ret;
}
T removeFirst() {
return remove(0);
}
T removeLast() {
return remove(size - 1);
}
void removeElement(T e) {
int index = find(e);
if (index != -1)
remove(index);
}
private:
void resize(int newCapacity) {
T *newData = new T[newCapacity];
for (int i = 0; i < size; i++)
newData[i] = data[i];
delete[] data;
data = newData;
capacity = newCapacity;
}
};
int main() {
MyArrayList<int> arr;
for (int i = 0; i < 10; i++)
arr.addLast(i);
arr.add(1, 100);
std::cout << arr.get(1) << std::endl;
arr.remove(2);
arr.removeElement(4);
for (int i = 0; i < arr.getSize(); i++)
std::cout << arr.get(i) << " ";
std::cout << std::endl;
return 0;
}
```
这个MyArrayList实现了动态扩展,可以在插入元素时自动扩容,也可以在删除元素时自动缩容。同时,还实现了常见的数组操作函数,例如在指定位置插入元素、在末尾添加元素、在头部添加元素、获取指定位置的元素、修改指定位置的元素、查找指定元素是否存在、查找指定元素的位置、删除指定位置的元素、删除第一个元素、删除最后一个元素、删除指定元素等。
阅读全文