Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
If C++ Objects Are Unrelated, Are They Equal? (drdobbs.com)
16 points by AndreyKarpov on Jan 28, 2013 | hide | past | favorite | 3 comments


A nifty way to implement a lexicographic ordering in C++11:

    struct Thing { int a, b; };
 
    bool compare(const Thing& t1, const Thing& t2)
    {
        return std::tie(t1.a, t1.b) < std::tie(t2.a, t2.b);
    }
Basically, this creates two tuples-of-references to the Thing members and compares the tuples lexicographically. Modern compilers optimize out all the tuple stuff and emit code basically indistinguishable from a hand-written variant like the following:

    bool compare(const Thing& t1, const Thing& t2)
    {
        return t1.a < t2.a || (t1.a == t2.a && t1.b < t2.b);
    }


That's really nice. I haven't written C++ for a while, and certainly not since std:tie<> became widely available. But I'll keep this in mind if I have to go down that road again.


> One of these sets has only a single element, namely 0. The others have two elements each:

Except for the other one-element set, containing INT_MIN.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: