std :: binary_search的自定义比较函数

时间:2011-11-03 22:13:35

标签: c++ stl binary-search

此代码有问题吗?

bool Spellcheck::smart_comp(string value, string key){
    return true;
}

void func(){
    std::string aprox_key = "hello";
    if(std::binary_search(this->words.begin(), this->words.end(), aprox_key, smart_comp)){
        std::cout << "Found" << std::endl;
    }
}

我正在尝试编写自己的比较函数来比较binarysearch中的字符串

我收到以下错误:

xyz.cpp:40:85: error: no matching function for call to ‘binary_search(std::vector<std::basic_string<char> >::iterator, std::vector<std::basic_string<char> >::iterator, std::string&, <unresolved overloaded function type>)’
xyz.cpp:40:85: note: candidates are:
/usr/include/c++/4.6/bits/stl_algo.h:2665:5: note: template<class _FIter, class _Tp> bool std::binary_search(_FIter, _FIter, const _Tp&)
/usr/include/c++/4.6/bits/stl_algo.h:2698:5: note: bool std::binary_search(_FIter, _FIter, const _Tp&, _Compare) [with _FIter = __gnu_cxx::__normal_iterator<std::basic_string<char>*, std::vector<std::basic_string<char> > >, _Tp = std::basic_string<char>, _Compare = bool (Spellcheck::*)(std::basic_string<char>, std::basic_string<char>)]
/usr/include/c++/4.6/bits/stl_algo.h:2698:5: note:   no known conversion for argument 4 from ‘<unresolved overloaded function type>’ to ‘bool (Spellcheck::*)(std::basic_string<char>, std::basic_string<char>)’

感谢任何帮助...

3 个答案:

答案 0 :(得分:4)

  

此代码有问题吗?

bool Spellcheck::smart_comp(string const value, string const key){
  return true;
}

除了它总是返回true?是的,基本问题是成员函数具有隐式参数this,因此签名与预期谓词的签名不匹配。您应该执行此功能static或甚至是免费功能(如果需要,可以friend编辑)。此外,您每次都在复制strings,最好通过const引用来获取参数以避免不需要的副本。

如果谓词的实际结果取决于Spellcheck对象的状态,则必须将该状态绑定到成员函数,以便使用适当的签名创建函数对象:

std::binary_search(
    this->words.begin(), this->words.end()
  , std::bind( &Spellcheck::smart_comp, this )
);

答案 1 :(得分:2)

您正在尝试传递一个非静态成员函数,该函数不能转换为所需的二进制函数(由于具有三个实际参数)。

尝试声明smart_comp函数static。 (当然,你不能引用实例成员;如果你需要有状态,你将不得不写一个完整的函子。)

答案 2 :(得分:1)

假设this->words的类型为std::vector<std::string>funcSpellcheck的成员,则可以将smart_comp声明为{{1} }}。但我会在你的班级设计上三思而后行。

相关问题