← Patterns

Lexicographic ordering

12345678910111213141516171819#include <tuple> class foo { public: foo(int n_, char c_, double d_) : n{n_}, c{c_}, d{d_} {} friend bool operator<(const foo& lh, const foo& rh) { return std::tie(lh.n, lh.c, lh.d) < std::tie(rh.n, rh.c, rh.d); } private: int n; char c; double d; };

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Implement a lexicographic ordering over class members.

Description

The class foo, on lines 3–19, has three member variables n, c and d declared on lines 16–18. We wish to implement an ordering relation for foo where these members are compared lexicographically.

Getting an ordering relation right with 3 elements or more is tedious and error-prone. Fortunately, the standard library provides a lexicographic ordering over std::tuple, which we can utilise.

The less-than operator for foo defined on lines 10–14 compares the member n first, then c if the ns are equal, and finally the member d if both the ns and cs are equal. To achieve this, we use std::tie on line 12 and line 13 to create std::tuples containing references to the members of the left operand and right operand respectively. The comparison of these std::tuples provides a lexicographic ordering over these members.

Contributors

  • Joseph Mansfield
  • Bjorn Fahller

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share