实现运算符&在C ++中 [英] Implementing operator< in C++

查看:164
本文介绍了实现运算符&在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有几个数字字段,如:

I have a class with a few numeric fields such as:

class Class1 {
    int a;
    int b;
    int c;
public:
    // constructor and so on...
    bool operator<(const Class1& other) const;
};

我需要使用此类的对象作为 std中的键: :map 。因此,我实现运算符< operator 在这里使用的最简单的实现是什么?

I need to use objects of this class as a key in an std::map. I therefore implement operator<. What is the simplest implementation of operator< to use here?

EDIT:
可以假设< 的含义,以便保证唯一性,只要任何字段不等。

The meaning of < can be assumed so as to guarantee uniqueness as long as any of the fields are unequal.

编辑2:

一个简单的实现:

bool Class1::operator<(const Class1& other) const {
    if(a < other.a) return true;
    if(a > other.a) return false;

    if(b < other.b) return true;
    if(b > other.b) return false;

    if(c < other.c) return true;
    if(c > other.c) return false;

    return false;
}

这篇文章背后的全部原因是我发现上面的实现太冗长。

The whole reason behind this post is just that I found the above implementation too verbose. There ought to be something simpler.

推荐答案

这取决于排序对你是否重要。如果没有,你可以这样做:

It depends on if the ordering is important to you in any way. If not, you could just do this:

bool operator<(const Class1& other) const
{
    if(a == other.a)
    {
         if(b == other.b)
         {
             return c < other.c;
         }
         else
         {
             return b < other.b;
         }
    }
    else
    {
        return a < other.a;
    }
}

这篇关于实现运算符&在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆