C++ - Class Template

这篇博客探讨了一个C++模板类`AddElements`的实现,该类根据输入的数据类型(字符串、整数或浮点数)进行元素的拼接或相加操作。示例输入和输出展示了如何使用这个模板类处理不同类型的数据,并给出了相应的结果。博客着重于模板类在处理不同类型数据时的灵活性和泛用性。
摘要由CSDN通过智能技术生成

Class Template

Input Format

The first line contains an integer n. Input will consist of n+1 lines where n is the number given in the first line of the input followed by n lines.

Each of the next line contains the type of the elements provided and depending on the type, either two strings or two integers or two floating point numbers will be given. The type will be one of int, float or string types only. Out of the following two elements, you have to concatenate or add the second element to the first element.

Output Format

The code provided in the code editor will use your class template to add/append elements and give the output

Sample Input:

3
string John Doe
int 1 2
float 4.0 1.5

Sample Output:

JohnDoe
3
5.5

Explanation

“Doe” when appended with “John” gives “JohnDoe”. 2 added to 1 gives 3, and 1.5 added to 4.0 gives 5.5.

Solution

template <T class> class AddElements {
	public:
		T element;
		AddElements (T i){
			element= i;
		}
		T add (T i){
			return element+i;
		}
		T concatenate (T i){
			return element+i;
		}	
};

Full Code

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;

/*Write the class AddElements here*/
template <class T> class AddElements {
    public:
        T element;
        AddElements (T i){
            element = i;
        }  
        T add (T i){
            return element+i;
        }
        T concatenate (T i){
            return element+i;
        }
};

int main () {
  int n,i;
  cin >> n;
  for(i=0;i<n;i++) {
    string type;
    cin >> type;
    if(type=="float") {
        double element1,element2;
        cin >> element1 >> element2;
        AddElements<double> myfloat (element1);
        cout << myfloat.add(element2) << endl;
    }
    else if(type == "int") {
        int element1, element2;
        cin >> element1 >> element2;
        AddElements<int> myint (element1);
        cout << myint.add(element2) << endl;
    }
    else if(type == "string") {
        string element1, element2;
        cin >> element1 >> element2;
        AddElements<string> mystring (element1);
        cout << mystring.concatenate(element2) << endl;
    }
  }
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值