在C++中,你可以通過繼承標準庫中的容器類(例如std::vector
、std::list
等)或者從頭開始創建一個新的容器類。這里我將給出一個簡單的示例,展示如何從頭開始創建一個基本的動態數組(類似于std::vector
):
#include<iostream>
#include<algorithm> // for std::copy
#include <stdexcept> // for std::out_of_range
template<typename T>
class MyVector {
public:
MyVector() : data(nullptr), size(0), capacity(0) {}
~MyVector() {
delete[] data;
}
// 復制構造函數
MyVector(const MyVector& other) {
data = new T[other.capacity];
std::copy(other.data, other.data + other.size, data);
size = other.size;
capacity = other.capacity;
}
// 賦值運算符
MyVector& operator=(const MyVector& other) {
if (this != &other) {
delete[] data;
data = new T[other.capacity];
std::copy(other.data, other.data + other.size, data);
size = other.size;
capacity = other.capacity;
}
return *this;
}
// 獲取元素
T& operator[](size_t index) {
if (index >= size) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
const T& operator[](size_t index) const {
if (index >= size) {
throw std::out_of_range("Index out of range");
}
return data[index];
}
// 添加元素
void push_back(const T& value) {
if (size == capacity) {
reserve(capacity == 0 ? 1 : capacity * 2);
}
data[size++] = value;
}
// 預分配內存
void reserve(size_t newCapacity) {
if (newCapacity > capacity) {
T* newData = new T[newCapacity];
std::copy(data, data + size, newData);
delete[] data;
data = newData;
capacity = newCapacity;
}
}
// 獲取當前大小
size_t getSize() const {
return size;
}
// 獲取當前容量
size_t getCapacity() const {
return capacity;
}
private:
T* data;
size_t size;
size_t capacity;
};
int main() {
MyVector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
for (size_t i = 0; i < vec.getSize(); ++i) {
std::cout<< vec[i] << " ";
}
std::cout<< std::endl;
return 0;
}
這個示例展示了一個簡單的動態數組類MyVector
,它支持添加元素、獲取元素、預分配內存等基本操作。你可以根據需要擴展這個類,添加更多的功能和優化性能。