-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvector_template.hpp
133 lines (112 loc) · 2.92 KB
/
vector_template.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#ifndef VECTOR_TEMPLATE_HPP
#define VECTOR_TEMPLATE_HPP
#include <iostream>
#include <stdexcept>
#include <algorithm>
template<typename T>
class myVector {
private:
T* data;
size_t size_;
size_t capacity_;
// 动态调整内存大小
void resizeIfNeeded() {
if (size_ >= capacity_) {
capacity_ = capacity_ == 0 ? 1 : capacity_ *2;
T* newData = new T[capacity_];
std::copy(data, data + size_, newData); // 复制现有数据到新分配的内存
delete[] data; // 释放旧内存
data = newData;
}
}
public:
myVector() : data(nullptr), size_(0), capacity_(0) {}
// 支持通过数组初始化
myVector(const T arr[], size_t arr_size) : size_(arr_size), capacity_(arr_size) {
data = new T[capacity_];
std::copy(arr, arr + arr_size, data);
}
// 支持通过列表初始化
myVector(std::initializer_list<T> init_list) : size_(init_list.size()), capacity_(init_list.size()) {
data = new T[capacity_];
std::copy(init_list.begin(), init_list.end(), data);
}
size_t size() const {
return size_;
}
size_t capacity() const {
return capacity_;
}
// 通过索引访问元素
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) {
resizeIfNeeded();
data[size_++] = value;
}
// 移除最后一个元素(栈)
void pop_back() {
if (size_ > 0) {
--size_;
}
}
// 按索引移除元素
void remove_at(size_t index) {
if (index >= size_) {
throw std::out_of_range("Index out of range");
}
std::move(data + index + 1, data + size_, data + index);
--size_;
}
// 按值移除元素
bool remove_element(const T& value) {
for (size_t i = 0; i < size_; ++i) {
if (data[i] == value) {
remove_at(i);
return true;
}
}
return false;
}
void print() const {
std::cout << "[";
for (size_t i = 0; i < size_; ++i) {
std::cout << data[i];
if (i < size_ - 1) {
std::cout << ", ";
}
}
std::cout << "]" << std::endl;
}
// 迭代器
T* begin() {
return data;
}
T* end() {
return data + size_;
}
const T* begin() const {
return data;
}
const T* end() const {
return data + size_;
}
void clear() {
size_ = 0;
}
~myVector() {
delete[] data;
}
};
#endif