内容:表(包括数组,链表,栈,队列)
参考文献:《数据结构与算法分析----C++语言描述(第四版)》
目的:希望各路大神指点一下
C++标准:C++11
操作系统:Ubuntu 18.04
编辑器:vs code
编译器:GCC 7.5.0
编译工具:CMake
vector弱鸡版实现
#include <algorithm>
#include <iostream>
namespace my
{
template <typename T>
class vector
{
public:
using size_type = unsigned long long;
using iterator = T *;
using const_iterator = const T *; // 注意是底层const
explicit vector(int init_size = 0)
: this_size(init_size),
this_capacity(init_size),
array(new T[init_size]) {
}
vector(const vector &a)
: this_size(a.this_size), this_capacity(a.this_capacity)
{
array = new T[this_capacity];
for (int k = 0; k != this_size; ++k)
{
array[k] = a.array[k];
}
}
vector &operator=(const vector &a)
{
vector copy = a;
std::swap(*this, copy);
return *this;
}
~vector() {
delete[] array; }
vector(vector &&a)
: this_size(a.this_size), this_capacity(a.this_capacity), array(a.array)
{
a.this_size = 0;
a.this_capacity = 0;
a.array = nullptr;
}
vector &operator=(vector &&a)
{
std::swap(this_size, a.this_size);
std::swap(this_capacity, a.this_capacity);
std::swap(array, a.array); //使用std::swap可以避免自赋值,对每个属性swap只是交换指针,
//不会有额外开销
return *this;
}
void reserve(int capacity)
{
if (capacity <= this_capacity)
return;
T *tmp_array = new T[capacity];
for (int k = 0; k != this_size; ++k)
{
tmp_array[k] = std::move(array[k]);
}
this_capacity = capacity;
delete[] array;
array = tmp_array;
}
void resize(int size)
{
if (size > this_capacity)
{
reserve(size * 2);
}
this_size = size;
}
T &operator[](int index) {
return array[index]; }
const T &operator[](int index) const {
return array[index]; }
size_type size() const {
return this_size; }
size_type capacity() const {
return this_capacity; }
bool empty() const {
return this_size == 0; }
void push_back(const T &o)
{
if (this_size == this_capacity)
reserve(this_capacity == static_cast<size_type>(0) ? 1
: this_capacity * 2);
array[this_size] = o;
++this_size;
}
void push_back(T &&o)
{
if (this_size == this_capacity)
reserve(this_capacity == static_cast<size_type>(0) ? 1
: this_capacity * 2);
array[this_size] = std::move(o);
++this_size;
}
void pop_back() {
--this_size; }
const T &back() const {
return array[this_size - 1]; }
T &