gpt4 book ai didi

c++ - std::binary_search 的自定义比较函数

转载 作者:行者123 更新时间:2023-11-30 00:39:45 35 4
gpt4 key购买 nike

这段代码有什么问题吗?

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

感谢任何帮助...

最佳答案

Is there any problem with this code?

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

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

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

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

关于c++ - std::binary_search 的自定义比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8002565/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com