C ++ BinarySearchTree插入元素

时间:2014-10-19 01:00:44

标签: c++

因此,当我尝试插入二叉搜索树时,我遇到了这些错误,我几乎坚持这个问题几个小时不知道该做什么,我找不到任何东西在互联网上提前帮助,谢谢。

In file included from Indexer.h:19,
                 from Indexer.cpp:20:
BinarySearchTree.h: In member function ‘void BinarySearchTree<Comparable>::insert(const Comparable&, BinarySearchTree<Comparable>::BinaryNode*&) [with Comparable = Word]’:
BinarySearchTree.h:108:   instantiated from ‘void BinarySearchTree<Comparable>::insert(const Comparable&) [with Comparable = Word]’
Indexer.cpp:109:   instantiated from here
BinarySearchTree.h:165: error: passing ‘const Word’ as ‘this’ argument of ‘bool Word::operator<(Word&)’ discards qualifiers
BinarySearchTree.h:167: error: no match for ‘operator<’ in ‘t->BinarySearchTree<Word>::BinaryNode::element < x’
Word.h:33: note: candidates are: bool Word::operator<(Word&)
make: *** [Indexer.o] Error 1

我认为创建它的代码来自Indexer.cpp第109行

Word接受两个参数,current是字符串,count对于此函数等于0。

Indexer.cpp

            BinarySearchTree<Word> filterTree;
  Line 109: filterTree.insert(Word(current, count));


BinarySearchTree.h

  void insert( const Comparable & x )
  {
    Line:108  insert( x, root );
  }

Word.cpp :operator<

bool Word::operator<(Word &RHS)
{
  if(m_wordText < RHS.GetWord())
    {
      return true;
    }
  else
    return false;
}

1 个答案:

答案 0 :(得分:0)

成员比较器应该(几乎)始终是constconst参数的函数,

bool Word::operator<(Word const&) const;

const函数中调用的任何函数也必须是const本身

std::string Word::GetWord() const;

(正如@NeilKirk正确地指出这可能会返回std::string const&)。

您应该了解const正确性,因为它可以阻止您在代码中犯下愚蠢的错误。

通常首选使用非成员比较器,因为它允许表达式的两边都使用转换运算符

bool operator<(Word const& lhs, Word const& rhs)
{
  return lhs.GetWord() < rhs.GetWord();
}