Is there a convenient way to wrap std::pair as a new type?

后端 未结 8 1088
梦谈多话
梦谈多话 2021-02-02 17:02

Often times I find myself using std::pair to define logical groupings of two related quantities as function arguments/return values. Some examples: row/col, tag/value, etc.

相关标签:
8条回答
  • 2021-02-02 17:52

    I must say that's a lot of thought just to make a simple struct.

    Overload operator< and operator== and you're done. I use that for a lot of code I write, mainly because I usually have more member variables to store than 2.

    struct MyStruct
    {
        std::string var1;
        std::string var2;
        bool var3;
    
        struct less : std::binary_function<struct MyStruct, struct MyStruct, bool>
        {
            bool operator() (const struct MyStruct& s1, const struct MyStruct& s2) const
                { if (var1== a2.var1) return var2 < a2.var2; else return var3 < a2.var3; }
        };
    };
    typedef std::set<struct MyStruct, MyStruct::less> MySet;
    

    or put these inside the class definition

    bool operator==(const MyStruct& rhs) const 
        { return var1 == rhs.var1 && var2 == rhs.var2 && var3 == rhs.var3; };
    bool operator<(const MyStruct& a2) const  
        { if (var1== a2.var1) return var2 < a2.var2; else return var3 < a2.var3; };
    

    The best reasons are that its easy to understand the above, they can be slipped into the class definition easily, and they are easy to expand if you find you need more variables later on. I would never try to overload std::pair when there's a much simpler solution.

    0 讨论(0)
  • 2021-02-02 17:55

    Don't use it.

    I hate std::pair exactly for this reason. You never know which is which, and since access to first and second are public you can't enforce contracts either.

    But after all, it's a matter of taste.

    0 讨论(0)
提交回复
热议问题