c++数组实现vector
时间: 2023-11-08 17:06:02 浏览: 97
C++vector的实现
5星 · 资源好评率100%
C++数组可以实现类似于vector的动态数组功能。具体实现方法如下:
```c++
template <typename T>
class Vector {
private:
T* data;
int size;
int capacity;
public:
Vector() {
data = new T[1];
size = 0;
capacity = 1;
}
void push_back(T val) {
if (size == capacity) {
T* newData = new T[2 * capacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
delete[] data;
data = newData;
capacity *= 2;
}
data[size++] = val;
}
T& operator[](int index) {
return data[index]; }
int getSize() {
return size;
}
};
```
阅读全文