0

DS Malik の書籍「C++ を使用したデータ構造」を読んでいます。次の検索機能について少し戸惑っています(リンクされたリストの場合)

マリクによれば、「検索項目がリストの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)

私の本能は、これらの && 演算子を使用して続行すると言っていますが、間違っている可能性があります。本のタイプミスですか、それとも何か抜けていますか?

もう 1 つの問題は、コンパイラが不平を言う次の行です。

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

それを修正するために、私はそれを

current = searchItem.first;

コンパイラはもう文句を言いませんが、親クラスから適切な保護されたメンバーにアクセスしていますか? nodeType<Type> *first( unorderedLinkList は、保護されたメンバーを持つlinkedListType親クラスから継承します)

編集:より多くのコード: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

4

1 に答える 1

2

while (current != NULL && !found)結構です。

言い換えれば、「私たちがリストの最後にいない間(つまり、それはcurrent != NULL意味します)アイテムは見つかりませんでした」. したがって、リストの最後にいるか、アイテムが見つかった場合、条件は真ではなくなります。

while (!(current == NULL || found))また、 ( De Morgan の法則を使用して)に翻訳することもできます。これは、大まかに「リストの最後にいるとき、またはアイテムが見つかったときに停止する」ことを意味します。「いつ停止するか」のロジックを理解するために、簡単なケースについて考えてみましょう。

  • while (!true)、これはwhile (false)大まかに「true の場合停止」を意味します (つまり、即座に)
  • while (!false)でありwhile (true)、大まかに「false の場合は停止する」という意味です (したがって、決して停止しません)。

firstは定義されていません...まあ、正確にはわかりませんが、標準のどこかにあります(私は専門家ではありません)、C++は時々奇妙です。関連する質問。回避策:

  • using linkedListType<Type>::firstクラスに入れる
  • firstで置き換えますthis->first
  • firstで置き換えますlinkedListType<Type>::first
于 2013-04-23T13:28:41.090 に答える