c++ - 如何实现 C++ 列表的 operator=?
问题描述
这是一个关于实现 c++ 列表的任务,所以如果有人要问“你为什么不使用 [非常方便的东西] 而不是列表”,答案是问我的教授,而不是我。我也不能改变我的标题。请注意,此版本的 list 只需能够接受 int 数据类型。假设我假设已经实现了列表的所有其他功能。
首先,我尝试过这个,它没有意识到我无法遍历 l ,它是恒定的(所以没有 l.curr = l.curr->next 等)。
Linkedlist& Linkedlist::operator=(const Linkedlist& l)
{
if (this != &l)
{
this->clear();
l.curr = l.head;
for (int i = 0; i < l.numElem; i++)
{
this->push_back(l.curr->data);
}
}
return *this;
}
我也试过这个,但我不能以任何方式修改 l 形状或形式,因为它是恒定的。类型限定符不兼容。
Linkedlist& Linkedlist::operator=(const Linkedlist& l)
{
if (this != &l)
{
this->clear();
for (int i = 0; i < l.numElem; i++)
{
this->push_back(l.front());
l.pop_front();
}
}
return *this;
}
抱歉/如果我需要提供更多信息,请告诉我。
解决方案
我无法迭代
l
哪个是恒定的(所以没有l.curr = l.curr->next
等)。
这不是您迭代对象节点的方式。您可以使用:
for (auto iter = l.head; iter != nullptr; iter = iter->next )
{
}
在您的情况下,您可以使用:
Linkedlist& Linkedlist::operator=(const Linkedlist& l)
{
if (this != &l)
{
this->clear();
for (auto iter = l.head; iter != nullptr; iter = iter->next )
{
this->push_back(iter->data);
}
}
return *this;
}
推荐阅读
- nlp - 如何使用缪斯获得对齐嵌入
- cocoapods - /bin/bash: ./configure: /bin/sh^M: bad interpreter: No such file or directory - CocoaPods 安装期间出错
- javascript - 如果值在数组中使用包含不起作用
- python - Python 要求我缩进,但是当我这样做时,该行不起作用。我应该怎么办?
- performance - Haskell中懒惰评估下的连接顺序和性能
- c# - 转换后如何使用变量
- dart - 什么是 Dart 原生实例
- python - 有没有更简单的方法来合并来自多个 DataFrame 块的 describe() 结果?
- firebase - 有没有办法通过用户的 UID 从 FirebaseAuth 中删除用户?
- python - lxml 如何定位和检索多个元素值?