定义运算符<为结构 [英] Defining operator< for a struct

查看:162
本文介绍了定义运算符<为结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时使用小 structs 作为地图中的键,因此我必须为它们定义一个运算符< 。通常,这看起来像这样:

I sometimes use small structs as keys in maps, and so I have to define an operator< for them. Usually, this ends up looking something like this:

struct MyStruct
{
    A a;
    B b;
    C c;

    bool operator<(const MyStruct& rhs) const
    {
        if (a < rhs.a)
        {
           return true;
        }
        else if (a == rhs.a)
        {
            if (b < rhs.b)
            {
                return true;
            }
            else if (b == rhs.b)
            {
                return c < rhs.c;
            }
        }

        return false;
    }
};

这看起来非常冗长和容易出错。有没有更好的方法,或者一些简单的方法来自动定义 operator struct class

This seems awfully verbose and error-prone. Is there a better way, or some easy way to automate definition of operator< for a struct or class?

我知道有些人喜欢使用 memcmp(this,&rhs, sizeof(MyStruct)) 0 ,但是如果在成员之间有填充字节,或者如果有 char 字符串数组可能包含垃圾,则这可能无法正常工作空终止符。

I know some people like to just use something like memcmp(this, &rhs, sizeof(MyStruct)) < 0, but this may not work correctly if there are padding bytes between the members, or if there are char string arrays that may contain garbage after the null terminators.

推荐答案

这是一个相当古老的问题,因此所有的答案都是过时的。 C ++ 11允许更加优雅和高效的解决方案:

This is quite an old question and as a consequence all answers here are obsolete. C++11 allows a more elegant and efficient solution:

bool operator <(const MyStruct& x, const MyStruct& y) {
    return std::tie(x.a, x.b, x.c) < std::tie(y.a, y.b, y.c);
}

为什么比使用 boost :: make_tuple ?因为 make_tuple 将创建所有数据成员的副本,这可能是昂贵的。相比之下, std :: tie ,将只创建一个引用的薄包装(编译器可能会完全优化)。

Why is this better than using boost::make_tuple? Because make_tuple will create copies of all the data members, which can be costly. std::tie, by contrast, will just create a thin wrapper of references (which the compiler will probably optimise away entirely).

事实上,上面的代码现在应该被视为实现对具有多个数据成员的结构的词典比较。

In fact, the above code should now be considered the idiomatic solution to implementing a lexicographical compare for structures with several data members.

这篇关于定义运算符&lt;为结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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