~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 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况