2 ms·
A nifty way to implement a lexicographic ordering in C++11: struct Thing { int a, b; }; bool compare(const Thing& t1, const Thing& t2) {
by Sharlin 14y ago
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);
}
- taybin 14y agoThat'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.