0

次のコードにエラーがあります。

(Visual Studio エラー:) エラー 5 エラー C2678: バイナリ '!=' : タイプ '`ノード' の左側のオペランドを取る演算子が見つかりません (または、受け入れ可能な変換がありません)

  template <class C, class T>
    C find2 ( C first , C last, T c )
    {
        //
        while ( first != last && *first != c )
        {
            ++first;
        }

        return first;
    }

    struct Node
    {
        Node(int a ,Node* b):val(a),next(b){};
        int val;
        Node* next;
    };

    template <class T>
    struct node_wrap
    {
        T* ptr;

        node_wrap ( T* p = 0 ) : ptr ( p ) {}
        Node& operator*() const {return *ptr;}
        Node* operator->() const {return ptr;}
        node_wrap& operator++ () {ptr = ptr->next; return * this;}
        node_wrap operator++ ( int ) {node_wrap tmp = *this; ++*this; return tmp;}

        bool operator== ( const node_wrap& i ) const {return ptr == i.ptr;}
        bool operator!= ( const node_wrap& i ) const {return ptr != i.ptr;}

    };
    bool operator== ( const Node& node, int n )
    {
        return node.val == n;
    }


    int main()
    {

        Node* node1=new Node(3,NULL);
        Node* node2=new Node(4,NULL);
        node1->next = node2;
        find2 ( node_wrap<Node>(node1), node_wrap<Node>(), 3) ) ;
        delete node1;
        delete node2;
        return 0;
    }

このコードの何が問題になっていますか?

4

2 に答える 2

3

Iteratorはタイプnode_wrap<Node>なので、ここ*firstに a を返しNodeます:

    while ( first != last && *first != c )

これには、!=の型と比較する演算子がありません。あなたはおそらく次のことを意味していました:cint

    while ( first != last && first->val != c )

これらは基本的に異なるタイプであり、互いに比較するべきではないため、operator==とを定義する他のアプローチよりもこれをお勧めします。operator!=Nodeint

于 2012-11-01T18:14:14.123 に答える
2

Nodeaと anを比較しようとしています (これは、 の実行時intに関数で行われます)。find2*first != c

operator==と比較するためにNodeを提供しましたが、同じことを行うために をint提供していませんoperator!=。1つ追加すると、これは機能するはずです。

于 2012-11-01T18:16:00.347 に答える