Creating a composite type from two enum classes, ready for STL map

后端 未结 6 1801
星月不相逢
星月不相逢 2021-02-14 05:26

I would like to create a composite type out of two enum classes.

enum class Color {RED, GREEN, BLUE};
enum class Shape {SQUARE, CIRCLE, TRIANGLE};

         


        
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-14 05:45

    What you are trying to express is that to determine the order of your Objects, you first need to compare the color, and then check the shape in case the color was the same. Instead of linearizing that, if would simply use boolean operators.

    friend bool operator< (const Object &lhs, const Object &rhs) 
    {
       return ( (lhs.color < rhs.color) 
               || ( (lhs.color == rhs.color ) && ( lhs.shape < rhs.color) ) )
    }
    

    EDIT: Actually, you can also use an upper bound for the number of objects, the behaviour will be the same:

    friend bool operator< (const Object &lhs, const Object &rhs) {
      return 10000*lhs.color+lhs.shape < 10000*rhs.color+rhs.shape;
    }
    

    but that introduces a "magic number" (so not such a good idea).

提交回复
热议问题