2009-07-17 57 views
1

我想实现一个使用指针的List类,并试图实现一个函数LOCATE(T x)其中T代表模板并返回元素x的第一个位置(如果找到),否则返回最后一个位置+ 1在C++模板中使用运算符

我的功能代码是

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; 

,但我得到一个错误信息

'布尔的std ::运算符==(常量的std :: istreambuf_iterator < _Elem,_Traits> &,常量的std :: istreambuf_iterator < _Elem,_Traits> &)':不能推导出模板参数的“常量性病:: istreambuf_iterator < _Elem,_Traits> &'from'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; 
+1

你可以发表节点的代码? – rlbond 2009-07-17 05:27:46

+0

你对节点的定义是什么样的?而完整的调用代码,以“列表 myList;”开头的代码,如上所示? 谢谢。 – 2009-07-17 05:30:46

+0

刚刚发布节点的定义和调用代码 – Jaelebi 2009-07-17 05:35:01

回答

1

尝试:

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

string::compare documentation

正如下面所指出的评论,运营商==应该工作。请仔细检查你是否有

#include <string> 
using std::string; 
0

std::istreambuf_iterator参考奇特如没有在你的代码显示证明它 - 可以请你告诉我们Node和任何其他代码在最小的失败示例中影响到此?试图从很偏代码和错误消息表示出的问题非常像拔牙...... - - !)

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 { ... 

什么与实际问题,肯定会有其他事情正在进行。

4

没有深入你的代码,我注意到几个问题。

首先,

locate(T n) 

应该

locate(const T& n) 

这样可以节省ň

,并要求一个愚蠢的问题的一个可能的副本,你确定你做:

#include <string> 
0

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

这会自行编译?

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

(每个C++程序员应该做出COUT < < “喇嘛” < <末;错字非常有趣)