📅  最后修改于: 2023-12-03 14:39:21.224000             🧑  作者: Mango
ArrayList
是 Java
中一个广受欢迎的动态数组实现,其提供了灵活的数组操作和自动扩展等功能。在 C++
中,我们可以通过使用模板和动态分配内存来实现类似的动态数组结构,从而达到与 ArrayList
相似的效果。
template <typename T>
class ArrayList {
private:
T* m_data;
int m_size;
int m_capacity;
void resize(int newCapacity) {
T* newData = new T[newCapacity];
for (int i = 0; i < m_size; i++) {
newData[i] = m_data[i];
}
delete[] m_data;
m_data = newData;
m_capacity = newCapacity;
}
public:
ArrayList() : m_data(nullptr), m_size(0), m_capacity(0) {}
~ArrayList() { delete[] m_data; }
int size() const { return m_size; }
bool isEmpty() const { return m_size == 0; }
void clear() {
delete[] m_data;
m_data = nullptr;
m_size = 0;
m_capacity = 0;
}
void add(const T& element) {
if (m_size == m_capacity) {
int newCapacity = m_capacity == 0 ? 1 : 2 * m_capacity;
resize(newCapacity);
}
m_data[m_size++] = element;
}
const T& get(int index) const {
if (index < 0 || index >= m_size) throw std::out_of_range("Index out of range");
return m_data[index];
}
T& operator[](int index) {
if (index < 0 || index >= m_size) throw std::out_of_range("Index out of range");
return m_data[index];
}
const T& operator[](int index) const {
if (index < 0 || index >= m_size) throw std::out_of_range("Index out of range");
return m_data[index];
}
void removeAt(int index) {
if (index < 0 || index >= m_size) throw std::out_of_range("Index out of range");
for (int i = index + 1; i < m_size; i++) {
m_data[i - 1] = m_data[i];
}
m_size--;
if (m_size < m_capacity / 4 && m_capacity > 0) {
int newCapacity = m_capacity / 2;
resize(newCapacity);
}
}
};
ArrayList<int> list;
list.add(42);
list.add(20);
list[0] = 10;
std::cout << list.get(1) << std::endl;
list.removeAt(0);
std::cout << list.size() << std::endl;
list.clear();
通过上述实现,我们可以获取与 Java
中 ArrayList
相似的灵活数组操作和自动扩展功能。但值得注意的是,由于 C++
中不提供垃圾回收机制,我们必须手动释放动态分配的内存,否则会发生内存泄漏的问题。