gpt4 book ai didi

c++ - 错误 C2672: 'operator __surrogate_func':使用 std::upper_bound 时未找到匹配的重载函数

转载 作者:搜寻专家 更新时间:2023-10-31 02:14:26 28 4
gpt4 key购买 nike

考虑下面的程序

struct slot {
int item;
bool operator<(const int& right) const {
return item < right;
}
slot(int item) : item(item) {}
};
int main() {
std::vector<slot> rails;
std::lower_bound(cbegin(rails), cend(rails), 5);
std::upper_bound(cbegin(rails), cend(rails), 5);
}

我正在使用 std::upper_bound 对 vector 进行二进制搜索,但在编译时失败了

c:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm(2609): error C2672: 'operator __surrogate_func': no matching overloaded function found

考虑到 std::upperbound使用 operator<对于不使用谓词的隐式比较,我找不到编译器提示的正当理由。此外,错误消息不是很有意义,因为我没有看到在这里使用代理函数的原因。即使是使用仿函数的情况 less<> , 这应该不是问题 slot与整数的可比性较低。值得注意的是 std::lower_bound有可接受的语法。

引用:http://rextester.com/WKK72283

最佳答案

作为std::upper_bound的规范明确指出,它应用与左侧参数值和右侧序列元素的比较。 IE。在你的情况下是 int < slot比较。你的operator <不支持按该特定顺序排列的比较。

对于 std::upper_bound你需要

bool operator <(int left, const slot &s)
{
return left < s.item;
}

不能作为成员函数实现。

与此同时,std::lower_bound应用与右侧参数值的比较,即 slot < int比较。

您的原始实现适用于 std::lower_bound , 但不适用于 std::upper_bound .

关于c++ - 错误 C2672: 'operator __surrogate_func':使用 std::upper_bound 时未找到匹配的重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940394/

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