我很难弄清楚如何在我的双向列表类中实现5的规则。我得到了它们的概念,它只是失去了如何编码它。我已经尝试过析构函数和复制操作符,但是在一个站点上仍然继续前进。感谢任何帮助/指导。
析/复制:
~DList() {
Node* current = front_;
while (current != back_)
{
front_ = front_->next_;
delete current;
current = front_;
}
}
// copy ctor
DList(const DList& rhs) {
const Node* current = rhs.front_;
Node* temp = nullptr;
if (current != back_)
{
front_ = new Node(current->data_);
temp = front_;
current = current->next_;
}
while(current != back_)
{
Node* nn = new Node(current->data_);
temp->next_ = nn;
temp = temp->next_;
current = current->next_;
}
}
DList& operator=(const DList& rhs){ //copy assignment // <<---not sure where to begin
列出ctor:
DList() {
//Node* front_;
front_ = new Node(); // creating front sentinel
//Node* back_;
back_ = new Node(); // creating back sentinel
//make them point to eachother
front_->next_ = back_;
back_->prev_ = front_;
listSz = 0;
}
主:
DList<int> list;
DList<int> list2;
DList<int>::const_iterator it;
cout << list.size() << endl;
list.push_front(1);
list.push_front(2);
list.push_back(3);
list.push_front(4);
list.print();
std::cout << endl;
list2.push_front(11);
list2.push_front(12);
list2.push_back(13);
list2.push_front(14);
list2.print();
list2 = list;
list2.print();
答案 0 :(得分:1)
如果你有一个工作副本构造函数(不使用赋值运算符)和析构函数,赋值运算符就可以这样:
#include <algorithm>
//...
DList& operator=(const DList& rhs)
{
DList temp(rhs);
std::swap(temp.front_, front_);
std::swap(temp.back_, back_);
std::swap(temp.listSz, listSz);
return *this;
}
这主要使用copy / swap idiom。从传入的DList
创建临时对象,临时对象的内部与当前对象的内部交换。然后临时与旧的内部结束了。