- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
考虑下面的程序
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
有可接受的语法。
最佳答案
作为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/
考虑下面的程序 struct slot { int item; bool operator rails; std::lower_bound(cbegin(rails), cen
我是一名优秀的程序员,十分优秀!