std :: map,只对一个变量排序的自定义键类型 [英] std::map, custom key type with sorting only on one variable

查看:137
本文介绍了std :: map,只对一个变量排序的自定义键类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个键类型:

struct KeyT {
    uint32_t timestamp;

    // example!
    uint32_t a;
    uint32_t b;
    uint32_t c;
    uint32_t d;
    uint32_t e;
    // ...

    bool operator== (const KeyT& key) const
    {
        if(timestamp == key.timestamp && a == key.a && b == key.b && d == key.d && c == key.c && e == key.e)
            return true;
        return false;

    }
    bool operator< (const KeyT& key) const
    {
        if(timestamp < key.timestamp)
            return true;
        else if(timestamp == key.timestamp && a < key.a && b < key.b && c < key.c && d < key.d && e < key.e)
            return true;
        else if(timestamp == key.timestamp && a == key.a && b < key.b && c < key.c && d < key.d && e < key.e)
            return true;
        else if(timestamp == key.timestamp && a == key.a && b == key.b && c < key.c && d < key.d && e < key.e)
            return true;
        else if(timestamp == key.timestamp && a == key.a && b == key.b && c == key.c && d < key.d && e < key.e)
            return true;
        else if(timestamp == key.timestamp && a == key.a && b == key.b && c == key.c && d == key.d && e < key.e)
            return true;
        // ..
        return false;
    }
};

现在,我真的不在乎成员vars a,b,c,d ,e,我唯一要确保的是地图是在时间戳上排序的。我也只是意识到,如果我有两个实例KeyT一,二,其中一切都是相同的,除了d,然后,两个,一个是假的。解决这个问题的唯一方法是对所有成员变量的所有可能的组合进行比较。我相当确定我缺少一些明显的东西,那么这种情况下最好的解决方案是什么?

Now, I don't really care about the sorting on member vars a, b, c, d, e, the only thing I want to ensure is that the map is sorted on timestamp. I also just realized that if I have two instances of KeyT one, two, where everything is the same except for "d", then both one < two, and two < one would be false. The only way to fix that is to write comparisons for all possible combinations of all member variables.. I'm fairly certain I'm missing something obvious, so what's the best solution in this case?

谢谢!

推荐答案

我认为这是你需要的:

bool operator< (const KeyT& key) const
{
    if(timestamp != key.timestamp) return timestamp < key.timestamp;
    else if ( a != key.a ) return a < key.a;
    else if ( b != key.b ) return b < key.b;
    else if ( c != key.c ) return c < key.c;
    else if ( d != key.d ) return d < key.d;
    else return e < key.e;
}

这是一个明智的丑陋模式,您想在可比类中排序的变量。

This is a sensible if ugly pattern to use whenever you have a prioritised list of variables you want to sort on within a comparable class.

这篇关于std :: map,只对一个变量排序的自定义键类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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