1

我正在尝试使用指针实现一个 List 类,并尝试实现一个函数 LOCATE(T x),其中 T 用于模板,如果找到则返回元素 x 的第一个位置,否则返回最后一个位置 + 1。

我的功能代码是

template<class T>
    int List<T>::locate(T n) const
    {
        int size = end();
        Node<T> * p = head_;

        for (int i = 0; i < size; i++)
        {
            if (p->data() == n) // fails on this line
                return i;
            p = p->link();
        }
        return size; // if no match found
     }

我用 T 作为字符串初始化我的列表

List<string> myList;

但我收到一条错误消息

'bool std::operator ==(const std::istreambuf_iterator<_Elem,_Traits> &,const std::istreambuf_iterator<_Elem,_Traits> &)' : 无法推导出 'const std::istreambuf_iterator<_Elem 的模板参数, _Traits> &' 来自 'std::string

即使为字符串类定义了“==”运算符,为什么还会出现错误?'

节点的代码是

template<typename T>
class Node
{
  public:

    // Constructors
    Node();
    Node(T d, Node<T> * l = NULL);

    //Inspectors 
    T data() const;
    Node<T> * link() const;

    // Mutators 
    void data(T d); // assigns new value to Node
    void link(Node<T> * l); // points this Node to a different one

    // Destructor
    ~Node();

    private:
  Node<T> * link_;
  T data_;
};

template<typename T>
    T Node<T>::data() const
    {
        return data_;
    }
template<typename T>
    Node<T>* Node<T>::link() const
    {
        return link_;
    }

调用代码是

List<string> test;
test.add("abc");
cout << test.locate("abc") << endl;
4

5 回答 5

4

在没有深入了解您的代码的情况下,我注意到了几个问题。

首先,

locate(T n) 

应该

locate(const T& n)

这保存了 n 的可能副本

问一个愚蠢的问题,你确定你已经完成了:

 #include <string>
于 2009-07-17T05:44:38.957 回答
1

尝试 :

if( n.compare(p->data()) == 0 )

字符串::比较文档

正如下面的评论所指出的, operator== 应该可以工作。请仔细检查您是否有

#include <string>
using std::string;
于 2009-07-17T05:42:32.517 回答
0

引用std::istreambuf_iterator是奇特的,因为您显示的代码中没有任何内容可以证明这一点 - 您能否在一个最小的失败示例中向我们展示Node以及其他任何代码对此有何影响?试图从非常部分的代码和错误消息中证明问题就像拔牙......!-)

于 2009-07-17T05:29:35.710 回答
0

这看起来不错,我看不到std::istreambuf_iterator图片是如何进入的......

您可能想要调整的一件事是采用const T&而不是T作为您的方法的参数,例如

  Node(const T& d, Node<T> * l = NULL);
  void data(const T& d);

  int List<T>::locate(const T& n) const { ...

实际问题是什么,肯定会有其他事情发生。

于 2009-07-17T05:40:15.203 回答
0

开始删除代码,直到它再次工作。一些错字或流氓宏或冲突的命名空间搞砸了。

这会自己编译吗?

string data = "bla";
Node<string> p("bla");
bool b = p.data() == data;

(每个 C++ 程序员都应该做一个 cout << "bla" << end; 错字。非常有趣)

于 2009-07-17T05:45:06.770 回答