Operator< and strict weak ordering

前端 未结 6 1976
醉酒成梦
醉酒成梦 2020-11-22 03:51

How to define operator< on n-tuple (for example on 3-tuple) so that it satisfy strict weak ordering concept ? I know that boost library has

6条回答
  •  执念已碎
    2020-11-22 04:23

    ...a new answer to a very old question, but the existing answer miss the easy solution from C++11...

    C++11 solution

    C++11 onwards provides std::tuple, which you can use to store your data. tuples have a matching operator< that initially compares the left-most element, then works along the tuple until the outcome's clear. That's suitable for providing the strict weak ordering expected by e.g. std::set and std::map.

    If you have data in some other variables (e.g. fields in a struct), you can even use std::tie() to creates a tuple of references, which can then be compared to another such tuple. That makes it easy to write operator< for specific member-data fields in a user-defined class/struct type:

    struct My_Struct
    {
        int a_;
        double b_;
        std::string c_;
    };
    
    bool operator<(const My_Struct& lhs, const My_Struct& rhs)
    {
        return std::tie(lhs.a_, lhs.b_, lhs.c_) < std::tie(rhs.a_, rhs.b_, rhs.c_);
    }
    

提交回复
热议问题