c++手写vector
时间: 2023-10-24 13:05:29 浏览: 96
关于C++vector
好的,这是手写 vector 的代码示例:
```
#include <iostream>
#include <memory>
template <typename T>
class MyVector {
public:
MyVector() : size_(0), capacity_(8) {
data_ = std::make_unique<T[]>(capacity_);
}
~MyVector() {
clear();
}
void push_back(const T& value) {
if (size_ == capacity_) {
reserve(capacity_ * 2);
}
data_[size_++] = value;
}
void pop_back() {
if (size_ > 0) {
--size_;
}
}
void clear() {
size_ = 0;
capacity_ = 8;
data_.reset(new T[capacity_]);
}
void reserve(int new_capacity) {
if (new_capacity <= capacity_) {
return;
}
std::unique_ptr<T[]> new_data = std::make_unique<T[]>(new_capacity);
for (int i = 0; i < size_; ++i) {
new_data[i] = data_[i];
}
data_ = std::move(new_data);
capacity_ = new_capacity;
}
T& operator[](int index) {
return data_[index];
}
const T& operator[](int index) const {
return data_[index];
}
int size() const {
return size_;
}
int capacity() const {
return capacity_;
}
private:
int size_;
int capacity_;
std::unique_ptr<T[]> data_;
};
int main() {
MyVector<int> vec;
for (int i = 0; i < 10; ++i) {
vec.push_back(i);
}
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
vec.pop_back();
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
vec.clear();
for (int i = 0; i < 10; ++i) {
vec.push_back(i);
}
vec.reserve(20);
for (int i = 0; i < vec.size(); ++i) {
std::cout << vec[i] << " ";
}
std::cout << std::endl;
return 0;
}
```
阅读全文