错误 C2672:“operator __surrogate_func”:使用 std::upper_bound 时找不到匹配的重载函数

Abh*_*jit 5 c++ visual-c++ c++11

考虑以下程序

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);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 std::upper_bound 对向量进行二分搜索,但在编译时失败

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

std::upperbound考虑到使用隐式比较而不使用谓词的事实operator<,我找不到编译器抱怨的合理理由。此外,错误消息不太有意义,因为我没有看到这里使用代理函数的原因。即使是使用函子的情况less<>,它也不应该成为问题,因为slot与整数的可比性较差。值得注意的是它std::lower_bound有一个可接受的语法。

参考: http: //rextester.com/WKK72283

AnT*_*AnT 7

正如规范中std::upper_bound明确指出的那样,它应用左侧参数值和右侧序列元素的比较。即在你的情况下,这将是int < slot比较。您的operator <不支持按该特定顺序排列的比较。

因为std::upper_bound你需要

bool operator <(int left, const slot &s)
{
  return left < s.item;
}
Run Code Online (Sandbox Code Playgroud)

不能作为成员函数实现。

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

您最初的实现适用于std::lower_bound,但不适用于std::upper_bound