gpt4 book ai didi

c++ - 派生类中的搜索函数,循环条件

转载 作者:行者123 更新时间:2023-11-28 03:18:25 24 4
gpt4 key购买 nike

阅读 D.S. Malik 的《使用 C++ 的数据结构》一书。我对下面的搜索功能有点疑惑,(对于链表)

根据 Malik 的说法,“如果搜索项是列表中的第 i 项,则 while 循环执行 i 次。以下是书中的确切代码(无注释)。

template <class Type>
bool unorderedLinkList<Type>::search(const Type& searchItem) const
{
nodeType<Type> *current;
bool found = false;
current = first;

while (current != NULL && !found)
if (current->info == searchItem)
found = true;
else
current = current->link;
return found;
}

一旦找到该项目,这个循环真的会停止吗?

while (current != NULL && !found)

我的直觉告诉我它会继续使用那些 && 运算符,但我可能错了。这只是书中的错字,还是我遗漏了什么?

另一个问题是我的编译器提示的以下行。

current = first; //error 'first' was not declared in this scope

所以为了修复它,我将它替换为

current = searchItem.first;

编译器不再提示,但它是否从父类访问了正确的 protected 成员? (unorderedLinkList继承自linkedListType父类,其中有protected nodeType<Type> *first成员)

编辑:更多代码:D

template <class Type>
struct nodeType
{
Type info;
nodeType<Type> *link;
};



template <class Type>
class linkedListType
{
public: //some removed for space
virtual bool search(const Type& searchItem) const = 0;

protected:
int count;
nodeType<Type> *first;
nodeType<Type> *last;

private:
void copyList(const linkedListType<Type>& otherList);
//function to make a copy of otherlist and assign to this list
};

编辑:派生类

template <class Type>
class unorderedLinkedList: public linkedListType<Type>
{
public:
bool search(const Type& searchItem) const;
}

编辑:VS Express 编译我的代码,但这个网站不会。请帮助? T_T http://ideone.com/SN2R99

最佳答案

while (current != NULL && !found)很好。

换句话说 - “虽然我们不在列表的末尾(这就是 current != NULL 的意思)并且还没有找到该项目”。因此,如果我们在列表末尾或已找到该项目,则条件将不再为真。

也可以翻译成while (!(current == NULL || found)) (使用 De Morgan's laws ),粗略地表示“当我们在列表末尾或找到该项目时停止”。要理解“何时停止”逻辑,请考虑一些简单的情况:

  • while (!true) ,即 while (false) ,粗略地表示“为真时停止”(因此立即)
  • while (!false) ,即 while (true) ,大致意思是“假时停止”(因此永远不会)

first没有定义是因为......好吧,我不太确定,它在某个地方的标准中(我不是专家),C++有时很奇怪。 Related question .解决方法:

  • 输入using linkedListType<Type>::first在你的类里面
  • 替换first通过 this->first
  • 替换first通过 linkedListType<Type>::first

关于c++ - 派生类中的搜索函数,循环条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16170324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com