Skip to content
Exercise · Templates · lesson 8 of 11

Exercise: Pair template

The class template Pair already has the fields first of type A and second of type B; write three of its methods. Pair<B, A> swapped() const returns a new pair with the same values in reverse order, and bool equals(const Pair<A, B>& other) const tells whether the pairs match in both fields. bool less_than(const Pair<A, B>& other) const checks whether this pair is less than other: the first fields are compared first and, if equal, the second fields.

Examples for the pair Pair<int, std::string> p{7, "seven"}:

  • p.swapped() → Pair<std::string, int>{"seven", 7}
  • p.equals({7, "six"}) → false
  • p.less_than({8, "apple"}) → true, p.less_than({7, "zebra"}) → true

Constraints: the checks use Pair<int, std::string> and Pair<std::string, int>; for equal pairs, less_than returns false.

pair.cpp — cpp
cpp · 18 lines
Ctrl+Enter run · Esc leave editor