gpt4 book ai didi

c++ - 算法::binary_search call中的预期主要表达式

转载 作者:行者123 更新时间:2023-12-02 11:06:09 24 4
gpt4 key购买 nike

我希望这不是痛苦的显而易见。我收到此神秘错误:

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<。但是,就像我之前说的那样,这将无济于事,因为您只会再次收到第一条错误消息。

基本上,您不能在链接列表上执行二进制搜索。

关于c++ - 算法::binary_search call中的预期主要表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9438585/

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