【发布时间】:2022-10-23 11:59:29
【问题描述】:
这是我创建的一个链表类的搜索方法。当 if 语句第一次为 false 时,for 循环“Find Nodes With Kind”会中断。我已经包含了整个方法,以及方法之外的相关常量、枚举、结构和变量。我已经尝试添加大括号并切换到 while 循环,结果相同。我已经在 CLion 和 OnlineGDB.com 中对其进行了测试。
没有错误。如果KIND 与位置 0 中的Bead 相同(例如copper),则返回包含位置 0 的指针,以及紧随其后的每个位置也包含相同的珠子类型,但不包含在第一个不是那种珠子的位置之后持有那种珠子的位置。如果不是在 0 位置的类型(例如 0 包含 silver 并搜索 copper),则返回 nullptr。
/* list.h */
/* ...blah, blah, blah... */
// Enumerated Data Types
// Bead Types
enum Bead: unsigned char{copper, silver, gold};
// Global Constants
const unsigned char X0 = 0, X1 = 1;
/* ...Other Stuff... */
class List
{
/* ...irrelevant stuff...*/
// Structures/Classes
struct Node // List's Node structure.
{
// Fields
Bead kind; // Holds the kind of bead.
Node * next; // Points to the next Node.
/* ...Other Stuff... */
};
// Fields
Node * head;
/* ...Other Stuff... */
public:
/* ...Other Stuff... */
// Methods
size_t length() const; // Length Retriever
/* ...Other Stuff... */
};
/* ...Other Stuff... */
/* list.cpp */
/* ...blah, blah, blah... */
// Search Method
size_t * List::search(const Bead & KIND)
{
// Method Variables/Constants
List::Node * node = head; // Pointer to move through the list.
const size_t L {length()}, // Size of list.
LP1 {L + X1}; // List + 1 For Length
size_t position[LP1], // Holds Positions Found
newSize = X1, // Size of returned array.
* returned; // Returned array.
// Error Check
if(!head) return nullptr; // Return nullptr if empty.
// Find Nodes With Kind
for(size_t i = X0; i < L; ++i) // Until end is reached:
if(node->kind == KIND) // If kind found:
{ // Add position to position[].
position[newSize++] = i; // Update newSize.
node = node->next; // Move to the next Node.
}
// When finished; set position[0] to newSize.
position[X0] = newSize;
// Return what was found; if anything.
if(newSize > X1)
{
returned = new size_t[newSize]; // Create correctly sized array,
for(size_t i = X0; i < newSize; ++i) // and copy data over.
*(returned + i) = position[i];
return returned; // Then return it.
}
// Return nullptr if nothing was found:
return nullptr;
}
/* ...Other Stuff... */
【问题讨论】:
-
你得到什么错误?
-
我没有收到任何错误。它只是停止。
-
你奇怪的缩进和命名没有帮助。为什么要创建可以按价值返回的新东西?
-
如果 if 语句评估为假,“节点”如何更新?
-
在我第五次遇到“等等等等……无关紧要的东西……其他的东西……”之后,我的眼睛呆滞了,但我仍然没有达到显然与你正在做的任何事情相关的代码部分.您似乎对 a 的概念有所了解最小的可重现的示例,但是此代码在到达它之前还有一段路要走。