~AC~ 2018-12-23 19:42 采纳率: 0%
浏览 632

求教一个自定义类的set容器问题

我自定义了一个类

class P {
public:
    P(int a, int b, int c) :m_a(a), m_b(b), m_c(c) {}

    bool operator == (const P&p)const {
        if (p.m_a == this->m_a && p.m_b == this->m_b && p.m_c == this->m_c)
            return true;
        return false;
    }
    bool operator<(const P&p) const{
        if (this->m_a != p.m_a) {
            if (this->m_a < p.m_a)
                return true;
            else
                return false;
        }
        if (this->m_b != p.m_b) {
            if (this->m_b < p.m_b)
                return true;
            else
                return false;
        }
        if (this->m_c != p.m_c) {
            if (this->m_c < p.m_c)
                return true;
            else
                return false;
        }
A:      return false;//**************************************
    }

public:
    int m_a;
    int m_b;
    int m_c;
};

声明了一个set<P>my_set;
我调用my_set.insert(P(1,2,3));3次,
当我在重载<那个函数里没加A语句时,发现3次都插入成功了,加了A语句发现
只插入了一次,想请问一下原因,我不是重载==了么,key值相同为什么还会重复插入呢?
  • 写回答

2条回答 默认 最新

  • zgbzsu2008 2018-12-23 12:16
    关注

    bool operator<(const P&p) const{
    if (this->m_a != p.m_a) {// 比较a
    if (this->m_a < p.m_a)
    return true;
    else
    return false;
    }
    else if (this->m_b != p.m_b) {// a相等比较b
    if (this->m_b < p.m_b)
    return true;
    else
    return false;
    }
    else if (this->m_c != p.m_c) {// a,b相等比较c
    if (this->m_c < p.m_c)
    return true;
    else
    return false;
    }
    return false;
    }

                你是判断分支没搞清楚
    
    评论

报告相同问题?

悬赏问题

  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile