【问题标题】:Custom Compare function for std::binary_searchstd::binary_search 的自定义比较函数
【发布时间】:2011-11-04 06:47:14
【问题描述】:

这段代码有问题吗?

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;
    }
}

我正在尝试编写自己的比较函数来比较二进制搜索中的字符串

我收到以下错误:

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

感谢任何帮助...

【问题讨论】:

    标签: c++ stl binary-search


    【解决方案1】:

    这段代码有问题吗?

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

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

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

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

    【讨论】:

    • 你的意思是说,我得把这个函数放到课外?
    • @Ringo:确实,如果它不依赖于对象内容。否则你需要一个函数对象来承载这种状态。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      假设this-&gt;words 的类型是std::vector&lt;std::string&gt; 并且funcSpellcheck 的成员,您可以解决将smart_comp 声明为static 的问题。但我会在你的班级设计上三思而后行。

      【讨论】:

      • 你为什么认为我的班级设计有缺陷?嗯,我同意另一点
      • @Ringo :因为没有明显的理由将比较逻辑放在除有状态仿函数之外的任何类中。
      猜你喜欢
      • 2012-06-30
      • 2020-10-02
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多