[C++面向对象]很眼熟的模板题

文章介绍了如何使用C++中的模板函数A,对整数数组计算平方和并转换为字符串,以及对字符串数组计算ASCII码和复制粘贴操作。
摘要由CSDN通过智能技术生成

描述

填写代码,按要求输出结果

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
//在此处补充你的代码

string int2string(int x) { return to_string(x); }
int int2squareint(int x) { return x * x; }

int string2int(string str) {
	int res = 0;
	for (string::iterator iter = str.begin(); iter != str.end(); ++iter)
		res += *iter;
	return res;
}
string string2longerstring(string str) { return str + str; }

int main() {

	int t;
	cin >> t;
	while (t--) {
		int b1[10];
		for (int i = 0; i < 10; ++i)

			cin >> b1[i];
		A<int, 10> a1 = b1;
		cout << a1.sum(2, 6, int2squareint) << endl;
		cout << a1.sum(2, 6, int2string) << endl;

		string b2[4];
		for (int i = 0; i < 4; ++i)
			cin >> b2[i];

		A<string, 4> a2 = b2;
		cout << a2.sum(0, 3, string2int) << endl;
		cout << a2.sum(0, 3, string2longerstring) << endl;
	}
	return 0;
}

输入

第一行是整数n,表示有n组数据
每组数据有2行
第一行是10个整数
第二行是4个不带空格的字符串,它们之间用空格分隔

输出

先输出10个整数里面的第3个到第7个的平方和
再输出10个整数里从第3个到第7个,按照字符串的方式,顺序连接的结果
再输出4个字符串里,第1个到第4个串中,所有字符的ASCII码加和得到的整数
再输出4个字符串里,第1个到第4个串,分别复制一遍后,按照字符串的方式,顺序连接的结果。

样例输入

1
1 2 3 4 5 6 7 8 9 10
Machine , Learning !

样例输出

135
34567
1586
MachineMachine,,LearningLearning!!

提示

3^2 + 4^2 + 5^2 + 6^2 + 7^2 = 135
“Machine,Learning!”中所有字符的ASCII码相加为1586

解题分析

使用模板函数里面常用的auto和decltype组合来创建一个通用的模板函数!

具体可以看本人博客C++学习笔记中关于这两个的详细说明。

代码演示
#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

// 在此处补充你的代码
template<class T,int size>
class A{
	T a[size];
public:
	A(T* b){
		for(int i=0;i<size;i++){
			a[i]=*(b+i);
		}
	}
	template <class T1>
	auto sum(int i,int j,T1 op)->decltype(op(a[0])){
		auto sumResult = decltype(op(a[0]))();
		for(int m=i;m<=j;m++){
			sumResult+=op(a[m]);
		}
		return sumResult;
	}
};

string int2string(int x) { return to_string(x); }
int int2squareint(int x) { return x * x; }

int string2int(string str) {
	int res = 0;
	for (string::iterator iter = str.begin(); iter != str.end(); ++iter)
		res += *iter;
	return res;
}
string string2longerstring(string str) { return str + str; }

int main() {
	
	int t;
	cin >> t;
	while (t--) {
		int b1[10];
		for (int i = 0; i < 10; ++i)
			
			cin >> b1[i];
		A<int, 10> a1 = b1;
		cout << a1.sum(2, 6, int2squareint) << endl;
		cout << a1.sum(2, 6, int2string) << endl;
		
		string b2[4];
		for (int i = 0; i < 4; ++i)
			cin >> b2[i];
		
		A<string, 4> a2 = b2;
		cout << a2.sum(0, 3, string2int) << endl;
		cout << a2.sum(0, 3, string2longerstring) << endl;
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值