参考了这篇博客:C++实现vector
练习模板类,命名空间,重载运算符的基础使用。加了个命名空间和对方括号的重载,使得可以通过索引访问数据。
#include <iostream>
namespace Morpheus {
template<typename T>
class vector {
private:
T* _first;
T* _last;
T* _end;
public:
vector(int size = 5) {
_first = new T[size];
_last = _first;
_end = _first + size;
}
~vector() {
delete[] _first;
_first = nullptr;
_last = nullptr;
_end = nullptr;
}
bool isEmpty() {
return _first == _last;
}
bool isFull() {
return _last == _end;
}
int size() {
return _last - _first;
}
void push_back(const T& x) {
if (isFull()) {
expand();
}
*_last++ = x;
}
void pop_back() {
if (!isEmpty()) {
_last--;
}
}
T operator[](const int& i) {
return _first[i];
}
private:
void expand() {
int len = _end - _first;
T* temp = new T[2 * len];
for (int i = 0; i < len; ++i) {
temp[i] = _first[i];
}
delete[] _first;
_first = temp;
_last = _first + len;
_end = _first + 2 * len;
}
};
}
int main() {
Morpheus::vector<double> v;
v.push_back(1.2);
v.push_back(1.3);
v.push_back(1.4);
for (int i = 0; i < v.size(); ++i) {
std::cout << v[i] << ",";
}
v.pop_back();
v.pop_back();
for (int i = 0; i < v.size(); ++i) {
std::cout << v[i] << ",";
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。