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

Custom Compare function for std::binary_search

本文关键字:比较 search 函数 std binary 自定义      更新时间:2023-10-16

这段代码有问题吗?

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>)’

这个代码有什么问题吗?

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

它总是返回true ?是的,基本问题是成员函数有一个隐式参数this,因此签名与预期谓词的签名不匹配。您应该执行这个函数static或甚至是一个自由函数(如果需要,friend ed)。此外,您每次都复制strings,最好通过const引用接受参数,以避免不必要的复制。

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

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

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

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

假设this->words的类型是std::vector<std::string>, funcSpellcheck的成员,您可以将smart_comp声明为static。但是我会再考虑一下你的班级设计。