将参数列表中的元素复制到调用对象中
Copying elements from parameter list into a calling object?
给定一个非空的单链表,该函数将形参表中的所有元素复制到调用对象中。
void AnyList::preFour(const AnyList& otherList) {
bool found = false;
Node* checkPtr = otherList.ptrToFirst;
//find first 4
while (checkPtr != nullptr && !found) {
if (checkPtr->getData() == 4) {
found = true;
}
else
checkPtr = checkPtr->getPtrToNext();
}
Node* current = ptrToFirst;
Node* copy = otherList.ptrToFirst;
while (current != checkPtr) {
current = current->getPtrToNext();
copy = copy->getPtrToNext();
}
}
这是我到目前为止的代码,我只需要一些指针如何复制参数列表到一定程度,同时将这些元素复制到调用对象(空列表)。我需要创建一个新节点吗?
这样做:
void AnyList::preFour(const AnyList& otherList) {
bool found = false;
Node* checkPtr = otherList.ptrToFirst;
//find first 4
while (checkPtr != nullptr && !found) {
if (checkPtr->getData() == 4) {
found = true;
}
else
checkPtr = checkPtr->getPtrToNext();
}
Node* current;
Node* copy = otherList.ptrToFirst;
/* This node is just to facilitate in copying.
It actually stores no relevant data.
It will be deleted after we are done with copying.*/
Node* dummy = new Node();
current = dummy;
while (copy != checkPtr) {
Node* temp = new Node();
current->next = temp; // Use appropriate method to set nextptr
current = current->getPtrToNext();
*current = *copy; // Use appropriate copy constructor or other method
copy = copy->getPtrToNext();
}
/* This method should return NULL if next pointer is not available.
If that is not so, just add a check here.
*/
ptrToFirst = dummy->getPtrToNext();
delete dummy;
}
由于调用对象的列表为空,我们首先需要为第一个节点分配空间。所以我先创建一个dummy
节点:
Node* dummy = new Node();
current = dummy;
当还没有达到停止条件时,继续使用该循环将参数表中的内容复制到调用对象的列表中。每次条件成功时,我们都必须创建一个新节点。这是因为必须为复制新元素分配空间。:
while (copy != checkPtr) {
Node* temp = new Node();
current->next = temp; // Use appropriate method to set nextptr
current = current->getPtrToNext();
*current = *copy; // Use appropriate copy constructor or other method
copy = copy->getPtrToNext();
}
请注意,复制后我将ptrToFirst
分配给dummy->getPtrToNext()
,然后将delete
分配给dummy
节点。
相关文章:
- 是什么让放置新调用对象的构造函数?
- 当我调用对象的方法时,对象的成员会发生变化
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 如何从构造函数副本 T(const T&)调用对象 T?
- C++17 如何保存泛型可调用对象以供以后使用
- 检查模板中 nullptr 的函数指针,了解任何类型的可调用对象
- 是否可以在编译时初始化对象的 C 样式函数指针,以便它调用对象的成员函数?
- 如何在C++中将可调用对象放入地图中?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 广义 std::function (std::any 表示可调用对象)
- c++ 替换调用对象方法的宏函数
- 将可调用对象传递给采用 std::function 的构造函数
- 双指针在使用 new 时不调用对象构造函数
- 可调用对象作为默认模板参数
- 只需调用对象即可获取对象数据
- 如果用户尝试从 JS 调用对象的未定义函数C++则回调C++代码
- 如何将当前替代类型的 std::variant 传递给可调用对象?
- C++对象本身作为参数调用对象的方法
- 从移交的类调用对象