c++ | set容器如何插入自定义对象

未实现比较函数时报错

In template: invalid operands to binary expression ('const complex' and 'const complex')

解决方案:set在插入时自动调用类中的<运算符重载进行排序,只需要在类中实现小于符号运算符重载即可

#include<iostream>
#include<set>
using namespace std;
class complex
{
public:
    double _a;
    double _b;

public:
    complex()
            :_a(0),
             _b(0)
    {}
    complex(double a, double b)
    :_a(a),
    _b(b)
    {}

    bool operator<(const complex& x)const
    {
        return _a < x._a;
    }

    void print() const
    {
        if(_b == 0)
            cout<<_a<<endl;
        else if(_a == 0)
            cout<<_b<<'i'<<endl;
        else
            cout<<_a<<" + "<<_b<<'i'<<endl;
    }
};


int main()
{
    set<complex> s;
    s.insert({1.1,2.2});
    s.insert({2.5,45.4});
    s.insert({-1.1,0});
    s.insert({-4.4,-2});
    s.insert({0,2.5});

    for(const complex& e : s)
        e.print();


    return 0;
}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值