表——Vector实现 :
不易被索引、插入、删除代价低( 已知位置,否则劣在于查找 )、查找低效;
这次实现过程错误百出,最后收获满满:
·对于嵌套类Node、iterator、const_iterator就在List类内实现吧;
·类内的函数实现顺序有时候会让编译器提示出List的对象并没有这个功能,但是运行还是可以的,坑死人啊;
·讨论一下*this,以下是我的理解:this 时刻指向当前对象,*this即为当前对象,对于类成员函数的第一个参数隐藏为(*this),有:
iterator begin() {
iterator ite(head); //方式一
return ++ite;
}
iterator begin() const {
return head->next; //方式二
}
这里用到iterator 的构造函数,让current=this了;
·对于即将销毁的右值List,只要接管了其首尾及大小,即可完成接管这条链:
List(List && rhs) :theSize{ rhs.theSize }, head{ rhs.head }
tail {rhs.tail} {
rhs.theSize = 0;
rhs.head = nullptr;
rhs.tail = nullptr;
}
·函数关系:
List()--->>>init();
clear()--->>>pop_front()--->>>erase();
pop()--->>>erase();
push()--->>>insert();
·类关系:
List的基础数据就是Node,同时Node也要提供给迭代器,在这里它就是一种直接被存取而不是通过方法访问的数据的类;
iterator继承自const_iterator,一些方法函数例如retrieve()只想让继承关系的能看到,而不让其他类有这些访问权限,那么就选择了protected;
由于iterator的构造函数是从指针变量显示地构造迭代器,这样不被允许,我不知道为什么啊,故不能让其公有,但是还要让List能访问,故friend class List<Object>;
贴上代码:
/*
list
·iterator 为 内嵌类类型,功能丰富
包含:begin()|end()|erase()|insert()|构造|检验
·list 需要Node节点类
包含:五大函数(其中operator = 为深层拷贝)
size()|empty()|clear()|back()|front()
push_back()|push_front()|pop_front()|pop_back()|
*/
template
class List
{
private:
//节点
struct Node
{
Object data;
Node * prev;
Node * next;
Node(const Object & d = Object{}, Node*p = nullptr, Node*n = nullptr)
:data{ d }, prev{ p }, next{ n } {};
Node(Object && d, Node*p = nullptr, Node*n = nullptr)
:data{ move(d) }, prev{ p }, next{ n } {};
};
public:
//迭代器
class const_iterator
{
public:
const_iterator() :current{ nullptr } {}
const Object & operator* () const { return retrive(); }
const_iterator & operator++() {
current = current->next;
return *this;
}
const_iterator & operator--() {
current = current->prev;
return *this;
}
const_iterator & operator++(int) {
const iterator old = *this;
++(*this);
return old;
}
const_iterator & operator--(int) {
const iterator old = *this;
--(*this);
return old;
}
bool operator==(const const_iterator & rhs) const {
return current == rhs.current;
}
bool operator!=(const const_iterator & rhs) const {
return !(*this == rhs);
}
protected:
Node * current;
const List