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

后端 未结 8 1244
梦谈多话
梦谈多话 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
        {
            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 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.

提交回复
热议问题