c++ set<> 类对象。使用自己的比较器给出错误 : C2804: binary 'operator <' has too many parameters

标签 c++ operator-overloading set

我写了一段c++代码如下:

#include<iostream>
#include<string>
#include<set>
using namespace std;

class data{
    int i;
    float f;
    char c;
public:
    data();
    data(int i,float f,char c);
};

data::data(int i,float f,char c){
    this->i=i;
    this->f=f;
    this->c=c;
};

class LessComparer{
    bool operator<( const data& a1, const data& a2 ) const{
        return( a1.i < a2.i ||
            (!(a1.i > a2.i) && (a1.f < a2.f)) ||
            (!(a1.i > a2.i) && !(a1.f > a2.f) && (a1.c < a2.c)));
    }
};

int main(){
    set<data,LessComparer> s;
    set<data,LessComparer>::iterator it;
    s.insert(data(1,1.3,'a'));
    s.insert(data(2,2.3,'b'));
    s.insert(data(3,3.3,'c'));
    if((it=s.find(data(1,1.3,'a'))!=s.end())
        cout<<(*it).i;
    cin.get();
    return 0;
}

在编译时给出第一个错误:

error: C2804: binary 'operator <' has too many parameters

还有 LessComparer 类中的许多其他错误。

我不熟悉这种重载。请帮助我更正代码。

谢谢。

最佳答案

LessComparer 需要实现 operator() 而不是 operator<

bool operator()( const data& a1, const data& a2 ) const

关于c++ set<> 类对象。使用自己的比较器给出错误 : C2804: binary 'operator <' has too many parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9783512/

相关文章:

c++ - 运算符仅以一种方式定义 - C++

python - 比较两组之间的每个元素?

ruby - 在 ruby​​ 中处理具有多个重复项的大量数据

c++ - 将 C++ 自定义类型公开给 QML

c++ - Windows 内核是否可以避免在用户模式下发生的损坏

c++ - 使用C++查找直线中的第三个点

c++ - 通过重载格式化链表输出 <<

c++ - 如何使用运算符重载添加类变量和 int 变量?

java - 比较作为映射的键和值的集合的大小

c++ - 使用大小为 8 的未初始化值。C++