Search⌘ K
AI Features

Solution: Pair Template

Explore how to implement a Pair class template in C++. Learn to store and compare pairs of values using templates, understand private template variables, helper functions, and how to override the equality operator for custom comparisons.

Storing and comparing pair values using templates

Let’s first execute the following solutions to store and compare the pair values using templates and see the code output. Then we’ll go through it line by line.

C++
#include <iostream>
template<typename T>
class Pair {
private:
T first;
T second;
public:
Pair(const T& firstValue, const T& secondValue)
: first(firstValue), second(secondValue) {}
T getFirst() const {
return first;
}
T getSecond() const {
return second;
}
void setFirst(const T& value) {
first = value;
}
void setSecond(const T& value) {
second = value;
}
bool operator==(const Pair<T>& other) const {
return (first == other.first) && (second == other.second);
}
};
template<typename T>
using ValuePair = Pair<T>;
int main() {
std::cout << "Pair:" << std::endl;
Pair<int> intPair(10, 20);
std::cout << "Integers( " << "First value: " << intPair.getFirst()
<< ", Second value: " << intPair.getSecond() << " )" << std::endl;
Pair<double> doublePair(3.14, 2.71);
std::cout << "Doubles( " << "First value: " << doublePair.getFirst()
<< ", Second value: " << doublePair.getSecond() << " )" << std::endl;
Pair<std::string> stringPair("Hello", "World");
std::cout << "Strings( " << "First value: " << stringPair.getFirst()
<< ", Second value: " << stringPair.getSecond() <<" )" << std::endl;
std::cout << "Value Pair:" << std::endl;
ValuePair<int> intValuePair(42, 42);
std::cout << "Integers( " << "First value: " << intValuePair.getFirst()
<< ", Second value: " << intValuePair.getSecond() << " )" << std::endl;
std::cout << "Equality Comparison:" << std::endl;
std::cout << "intPair == intValuePair: " << (intPair == intValuePair) << std::endl;
return 0;
}

Explanation

...