【问题标题】:no match for 'operator+' in sort in c++在 C++ 中排序中的“运算符+”不匹配
【发布时间】:2016-01-05 04:25:39
【问题描述】:

我已经定义了一个类

class Rent
{
    public:    
    int s_time, duration, price, e_time;
    Rent(int s, int d, int p)
    {
        s_time = s;
        duration = d;
        price = p;
        e_time = s + d;
    }
    bool operator<(Rent const &r1)
    {
        return e_time < r1.e_time;
    }
};

希望根据e_time 对其进行排序,所以我在Rent 上定义了&lt;,但是,我不断收到错误

rent.cpp:38:12: error: no match for ‘operator+’ (operand types are ‘std::vector<Rent>’ and ‘int’)

     sort(R, R+n);
              ^

当我尝试sort(R, R+n); 时。 RRent 类型的向量,n 是整数(向量的大小)。

除了上述之外,我尝试了这两种方法,但仍然失败!

sort(R, R + sizeof(R)/sizeof(R[0]));
sort(R.begin(), R.end());

我用 google 搜索并得到了一些使用 lambdas 的解决方案,但 sort() 的第二个参数再次是 int + custom_datatype 类型。

任何帮助都会很棒。

【问题讨论】:

  • 仅供参考,您应该使用 initializer_list 而不是在构造函数的主体中执行复制分配。

标签: c++ sorting stl


【解决方案1】:
sort(R, R+n);
sort(R, R + sizeof(R)/sizeof(R[0]));

如果R 的类型为std::vector&lt;Rent&gt;,则将不起作用。这些行有两个问题:

  1. operator+() 没有为 std::vector 定义。
  2. 编译器期望 operator&lt;() 函数是 const 成员函数。

您可以通过将operator&lt;() 函数设为const 成员函数来修复它。

bool operator<(Rent const &r1) const
                           //  ^^^^^
{
    return e_time < r1.e_time;
}

这仍然没有解决第一个问题。

但是你应该可以使用:

sort(R.begin(), R.end());

在那之后。

理论上,您不必将operator&lt;() 函数设为非const 成员函数。看看http://en.cppreference.com/w/cpp/algorithm/sort。请参阅comp 参数的描述。它说:

比较函数的签名应该等价于:

bool cmp(const Type1 &a, const Type2 &b);

签名不需要有const &amp;,但函数对象不能修改传递给它的对象。

但是,并非所有编译器都遵守这一点。他们希望函数的签名能够与const 对象一起使用。

【讨论】:

  • 如何使它成为一个常量成员函数导致代码在这种情况下工作?我多次重载
  • 谢谢,让const 工作顺便说一句。但是你能说出这背后的逻辑吗?
  • 为什么要提出std::sortcomp 参数?这里没有使用重载,对吧?
  • @JamesAdkison,它不是一个明确指定的comp,而是默认的——operaor&lt;()函数——应该遵循相同的语义,即它需要与@987654345一起工作@对象。
  • This 对我有用,即使没有 operator&lt;const 成员函数。需要明确的是,我认为它应该是一个 const 成员函数,因为它不会修改类状态我只是想了解为什么它不适用于 OP。
【解决方案2】:

根据错误,Rstd::vector&lt;Rent&gt;,但代码如下:

sort(R, R+n);

仅适用于 C 样式数组。如果您想要适用于 C 数组和 std::vector 的通用代码,请将其写为:

std::sort( std::begin(R), std::end(R) );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    相关资源
    最近更新 更多