C++ program to add different items with class templates

C++Server Side ProgrammingProgramming

Suppose we want to make a class that can add two integers, two floats and two strings (string addition is basically concatenating strings). As input at first we take a number n represents there are n different operations. In each operation the first item is the type [int, float, string] and second and third are two operands. So each line will contain three elements. We shall have to read them and do the operations as mentioned.

So, if the input is like

5
int 5 7
int 6 9
float 5.25 9.63
string hello world
string love C++

then the output will be

12
15
14.88
helloworld
loveC++

To solve this, we will follow these steps −

  • Define a class called AddItems with class template. It has two functions add() and concatenate(). add() will add integers and floats, and concatenate() will concatenate strings.

  • From the main method, do the following

  • for initialize i := 0, when i < n, update (increase i by 1), do:

    • type := current type

    • if type is same as "float", then:

      • take two operands e1 and e2

      • create an object of AddItems of type float called myfloat with item e1

      • call myfloat.add(e2) and display

    • otherwise when type is same as "int", then:

      • take two operands e1 and e2

      • create an object of AddItems of type float called myint with item e1

      • call myint.add(e2) and display

    • otherwise when type is same as "string", then:

      • take two operands e1 and e2

      • create an object of AddItems of type float called mystring with item e1

      • call mystring.concatenate(e2) and display

Example

Let us see the following implementation to get better understanding −

#include <iostream>
using namespace std;
template <class T>
class AddItems {
    T element;
  public:
    AddItems (T arg) {
        element=arg;
    }
    T add (T e2) {
        return element+e2;
    }
    T concatenate (T e2) {
        return element+e2;
    }
};
int main(){
    int n,i;
    cin >> n;
    for(i=0;i<n;i++) {
        string type;
        cin >> type;
        if(type=="float") {
            float e1,e2;
            cin >> e1 >> e2;
            AddItems<float> myfloat (e1);
            cout << myfloat.add(e2) << endl;
        }
        else if(type == "int") {
            int e1, e2;
            cin >> e1 >> e2;
            AddItems<int> myint (e1);
            cout << myint.add(e2) << endl;
        }
        else if(type == "string") {
            string e1, e2;
            cin >> e1 >> e2;
            AddItems<string> mystring (e1);
            cout << mystring.concatenate(e2) << endl;
        }
    }
}

Input

5
int 5 7
int 6 9
float 5.25 9.63
string hello world
string love C++

Output

12
15
14.88
helloworld
loveC++
raja
Published on 07-Oct-2021 08:34:01
Advertisements