自定义std::binary_search的比较函数
Custom Compare function for std::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>)’
这个代码有什么问题吗?
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>
, func
是Spellcheck
的成员,您可以将smart_comp
声明为static
。但是我会再考虑一下你的班级设计。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 比较两个大小不等的映射c++