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

Search function in derived class, loop condition

本文关键字:循环 条件 函数 搜索 派生      更新时间:2023-10-16

阅读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;

编译器不再抱怨了,但是它是从父类访问正确的受保护成员吗?(unorderedLinkList继承自linkedListType父类,它保护了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_Thttp://ideone.com/SN2R99

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

In words -"当我们不在列表的末尾时(这就是current != NULL的意思)该项目尚未找到"。因此,如果我们在列表的末尾,或者项已经被找到,条件将不再为真。

你也可以把它翻译成while (!(current == NULL || found))(使用De Morgan的定律),意思是"当我们在列表的末尾或项目已经找到时停止"。要理解"when when"的逻辑,请考虑一些简单的情况:

  • while (!true),即while (false),意思是"为真时停止"(因此立即停止)
  • while (!false),即while (true),松散地表示"false时停止"(因此永远不会停止)

first没有定义,因为…嗯,我不太确定,它在标准的某个地方(我不是专家),c++有时很奇怪。相关的问题。解决方法:

  • using linkedListType<Type>::first放到你的类中
  • this->first代替first
  • first替换为linkedListType<Type>::first