错误C2672:'运算符__surrogate_func':使用std :: upper_bound时找不到匹配的重载函数 [英] error C2672: 'operator __surrogate_func': no matching overloaded function found when using std::upper_bound

查看:1354
本文介绍了错误C2672:'运算符__surrogate_func':使用std :: upper_bound时找不到匹配的重载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下程序

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来对向量进行二进制搜索,但编译时失败

I am using std::upper_bound to binary search a vector but fails while compiling

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 具有可接受的语法。

Considering the fact that std::upperbound uses operator< for implicit comparison without using a predicate, I cannot find a justified reason for the compiler to complain. Moreover, the error message is not quite meaningful as I do not see a reason for using a surrogate function here. Even if it is a case of using a functor less<>, it should not be an issue as slot is less comparable with an integer. It's worth noting that std::lower_bound has an acceptable syntax.

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

推荐答案

std :: upper_bound 的规范明确指出,它将比较与左侧的参数值和右侧的sequence元素进行比较。即在您的情况下为 int<广告位比较。您的运算符< 不支持按该特定顺序排列的比较。

As the specifications of std::upper_bound clearly states, it applies the comparison with the argument value on the left-hand side and the sequence element on the right-hand side. I.e. in your case that would be int < slot comparison. Your operator < does not support comparisons arranged in that specific order.

对于 std :: upper_bound 您将需要

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

不能作为成员函数实现。

which cannot be implemented as a member function.

同时, std :: lower_bound 将比较结果与右侧的参数值一起应用,即 slot< ; int 比较。

Meanwhile, std::lower_bound applies the comparisons with the argument value on the right-hand side, i.e. slot < int comparisons.

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

Your original implementation will work for std::lower_bound, but not for std::upper_bound.

这篇关于错误C2672:'运算符__surrogate_func':使用std :: upper_bound时找不到匹配的重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆