Comparison operators in C++

Level 4279 keystrokes

Overloads == and < for a Number class so that objects are compared by their value; 5 == 10 is false and 5 < 10 is true, printed as 0 1.

C++ code

1class Number {
// Private value used for the comparisons
2 int value;
3public:
4 Number(int v) : value(v) {}
// Defines a == b; const because comparing does not modify the object
5 bool operator==(const Number& other) const {
// Equal when the stored values are equal
6 return value == other.value;
7 }
// Defines a < b by comparing the values
8 bool operator<(const Number& other) const {
9 return value < other.value;
10 }
11};
12
// Two objects with the values 5 and 10
13Number a(5), b(10);
// false prints as 0 and true as 1: prints 0 1
14cout << (a == b) << " " << (a < b) << endl;

Output

0 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.

  • <× 11
  • (× 8
  • )× 8
  • ;× 6
  • =× 6
  • {× 4
  • }× 4
  • :× 2
  • .× 2
  • "× 2

More C++ examples at level 4

← C++ typing practice