Comparison Operators in C++

Level 5532 keystrokes

A defaulted operator<=> (the C++20 three-way comparison, or "spaceship" operator) compares the members in declaration order, so <, >, <= and >= work automatically; a defaulted <=> also provides ==. A friend operator<< prints versions as major.minor.patch.

C++ code

1class Version {
// Members in comparison order: major, then minor, then patch
2 int major_, minor_, patch_;
3public:
4 Version(int maj, int min, int pat) : major_(maj), minor_(min), patch_(pat) {}
5
// = default compares members in order; <, >, <=, >= and == become available
6 auto operator<=>(const Version& other) const = default;
7
// friend gives operator<< access to the private members
8 friend ostream& operator<<(ostream& os, const Version& v) {
// Prints the version as major.minor.patch
9 return os << v.major_ << "." << v.minor_ << "." << v.patch_;
10 }
11};
12
13Version v1(1, 2, 3), v2(1, 2, 4), v3(2, 0, 0);
14
// Same major and minor; patch 3 < 4: prints 1
15cout << v1 << " < " << v2 << ": " << (v1 < v2) << endl;
// major 1 < 2 decides it: prints 1
16cout << v2 << " < " << v3 << ": " << (v2 < v3) << endl;
// == also works: prints 1
17cout << v1 << " == " << v1 << ": " << (v1 == v1) << endl;

Output

1.2.3 < 1.2.4: 1
1.2.4 < 2.0.0: 1
1.2.3 == 1.2.3: 1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 53
  • "× 16
  • ,× 15
  • (× 12
  • )× 12
  • _× 9
  • ;× 8
  • =× 6
  • :× 5
  • .× 5

More C++ examples at level 5

← C++ typing practice