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() constreturns a new pair with the same values in reverse order;bool equals(const Pair<A, B>& other) consttells whether the pairs match in both fields;bool less_than(const Pair<A, B>& other) constchecks whether this pair is less thanother: thefirstfields are compared first and, if equal, thesecondfields.
Examples for the pair Pair<int, std::string> p{7, "seven"}:
p.swapped()→Pair<std::string, int>{"seven", 7}p.equals({7, "six"})→falsep.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.
Do not add extra #include lines unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.