Practice Template Class

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Problem: Create a template class called Pair that represents a pair of values. Implement member functions to set and retrieve the values of the pair. Write a program to create Pair objects with different data types, set their values, and display them.

cppCopy code

#include <iostream> // Template class representing a Pair template <typename T1, typename T2> class Pair { private:    T1 first;    T2 second; public:    // Constructor    Pair(const T1& val1, const T2& val2) {        first = val1;        second = val2;    }    // Function to set the values of the pair    void setValues(const T1& val1, const T2& val2) {        first = val1;        second = val2;    }    // Function to get the first value of the pair    T1 getFirst() const {        return first;    }    // Function to get the second value of the pair    T2 getSecond() const {        return second;    } }; int main() {    // Create Pair objects with different data types    Pair<int, double> pair1(10, 3.14);    Pair<std::string, bool> pair2("Hello", true);    // Set and display the values of pair1    pair1.setValues(20, 6.28);    std::cout << "Pair 1: (" << pair1.getFirst() << ", " << pair1.getSecond() << ")\n";    // Set and display the values of pair2    pair2.setValues("World", false);    std::cout << "Pair 2: (" << pair2.getFirst() << ", " << pair2.getSecond() << ")\n";    return 0; }

In this example, we create a template class called Pair that represents a pair of values. The template parameters T1 and T2 represent the types of the first and second values, respectively.

The Pair class includes member variables first and second to store the values.

The class provides member functions such as the constructor, setValues to set the values of the pair, getFirst to retrieve the first value, and getSecond to retrieve the second value.

In the main function, we create two instances of the Pair class: pair1 with integer and double types, and pair2 with string and boolean types. We set the values of the pairs using the setValues function and display the values using std::cout.

By running the program, you will see the output that displays the pairs with their respective values.

2. Essential C and Cpp Concepts

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support