Algorithm::binary_search 调用中的预期主要表达式
-
12-11-2019 - |
题
我希望这不是显而易见的。我收到这个神秘的错误:
fold.cpp:92: error: expected primary-expression before ‘)’ token
它所指的行是:
if (binary_search (corpus.begin(),corpus.end(), left, customArray::operator<(customArray)))
在使用更简单的调用后我遇到了这个错误:
if (binary_search (corpus.begin(),corpus.end(), left))
并收到此错误消息(重要的部分是最后的注释,说将其更改为上面的调用)
In function ‘bool std::binary_search(_ForwardIterator, _ForwardIterator, const _Tp&) [with _ForwardIterator = std::_List_iterator<customArray>, _Tp = std::string [3]]’:
fold.cpp:92: instantiated from here
/usr/include/c++/4.2.1/bits/stl_algo.h:4240: error: no match for ‘operator<’ in ‘__val < __i. std::_List_iterator<_Tp>::operator* [with _Tp = customArray]()’
/usr/include/c++/4.2.1/bits/stl_algo.h: In function ‘_ForwardIterator std::lower_bound(_ForwardIterator, _ForwardIterator, const _Tp&) [with _ForwardIterator = std::_List_iterator<customArray>, _Tp = std::string [3]]’:
/usr/include/c++/4.2.1/bits/stl_algo.h:4239: instantiated from ‘bool std::binary_search(_ForwardIterator, _ForwardIterator, const _Tp&) [with _ForwardIterator = std::_List_iterator<customArray>, _Tp = std::string [3]]’
fold.cpp:92: instantiated from here
/usr/include/c++/4.2.1/bits/stl_algo.h:2906: error: no match for ‘operator<’ in ‘__middle. std::_List_iterator<_Tp>::operator* [with _Tp = customArray]() < __val’
fold.cpp:16: note: candidates are: bool customArray::operator<(customArray)
本质上,我试图在自定义(数组类型)对象的链接列表上使用二分搜索。其余相关代码在这里:
// here is the custom class I am using in the list
class customArray
{
public:
// this is a somewhat lame way to compare, but it seems to work
bool operator< (customArray temp)
{
return array[0] < temp.array[0];
}
bool operator> (customArray temp)
{
return array[0] > temp.array[0];
}
bool operator== (customArray temp)
{
return ((array[0] == temp.array[0]) && (array[1] == temp.array[1]) && (array[2] == temp.array[2]));
}
string array[3];
};
//All of this stuff is in main
customArray one;
//some processing here to fill one
corpus.push_back (one);
// sort the list
corpus.sort();
corpus.unique();
string left [3];
if (binary_search (corpus.begin(),corpus.end(), left, customArray::operator<(customArray)))
{
}
我希望这很容易理解。如果有什么方法可以澄清,请告诉我。
解决方案
您的第一条错误消息是因为 binary_search
用途 <
在迭代器上,但列表的迭代器不支持 <
. 。此错误与您是否将比较函数作为参数传递给 binary_search
.
您的第二条错误消息是因为您在将函数作为参数传递时指定了类型。这与调用函数基本相同 f(int x)
代替 f(x)
, ,这在语法上是不正确的。应该只是 customArray::operator<
. 。但是,正如我之前所说,这对您没有帮助,因为您只会再次收到第一条错误消息。
基本上你不能在链表上执行二分搜索。
其他提示
您将您的函数的整个签名拨打您的函数与binary_search。你不需要那里的'bool'。
不隶属于 StackOverflow