use C++ You are given the following main function that creates a generic pair object…
- User
use C++ You are given the following main function that creates a generic pair object with integer type, sets the first and second to the given values, swaps the items and prints the items. Pair class is not provided. You are asked to provide implementation for Pair class so that the main method works successfully.
#include using namespace std; //your code goes here
int main() { Pair pair; int x=2, y=3; pair.setFirst(x); pair.setSecond(y); pair.print(); //prints-> 2 : 3 pair.swap(); pair.print(); //prints-> 3 : 2 return 0; }
- Assistant
Here's one possible implementation of the Pair class:
#include <iostream> using namespace std; template<typename T> class Pair { private: T first; T second; public: void setFirst(T value) { first = value; } void setSecond(T value) { second = value; } void swap() { T temp = first; first = second; second = temp; } void print() { cout << first << " : " << second << endl; } }; int main() { Pair<int> pair; int x=2, y=3; pair.setFirst(x); pair.setSecond(y); pair.print(); //prints-> 2 : 3 pair.swap(); pair.print(); //prints-> 3 : 2 return 0; }In this implementation, the Pair class is a generic class defined using the template keyword. It has two private data members,
firstandsecond, of type T. ThesetFirstandsetSecondmethods are used to set the values offirstandsecondrespectively. Theswapmethod swaps the values offirstandsecondusing a temporary variable. Theprintmethod prints the values offirstandsecondseparated by a colon. The main function demonstrates the usage of the Pair class by creating a Pair object of type int, setting its values, swapping them, and printing them.