c++编程练习 034:goodcopy

北大程序设计与算法(三)测验题汇总(2020春季)


描述

编写GoodCopy类模板,使得程序按指定方式输出

#include <iostream>
using namespace std;


template <class T>
struct GoodCopy {
// 在此处补充你的代码
};

int a[200];
int b[200];
string c[200];
string d[200];

template <class T>
void Print(T s,T e) {
	for(; s != e; ++s)
		cout << * s << ",";
	cout << endl;
}

int main()
{
	int t;
	cin >> t;
	while( t -- ) {
		int m ;
		cin >> m;
		for(int i = 0;i < m; ++i)
			cin >> a[i];
		GoodCopy<int>()(a,a+m,b);
		Print(b,b+m);
		GoodCopy<int>()(a,a+m,a+m/2);
		Print(a+m/2,a+m/2 + m);

		for(int i = 0;i < m; ++i)
			cin >> c[i];
		GoodCopy<string>()(c,c+m,d);
		Print(c,c+m);
		GoodCopy<string>()(c,c+m,c+m/2);
		Print(c+m/2,c+m/2 + m);
	}
	return 0;
}

输入
第一行是整数 t,表示数据组数
每组数据:
第一行是整数 n , n < 50
第二行是 n 个整数
第三行是 n 个字符串

输出
将输入的整数原序输出两次,用","分隔
然后将输入的字符串原序输出两次,也用 ","分隔

样例输入
2
4
1 2 3 4
Tom Jack Marry Peking
1
0
Ted

样例输出
1,2,3,4,
1,2,3,4,
Tom,Jack,Marry,Peking,
Tom,Jack,Marry,Peking,
0,
0,
Ted,
Ted,

来源
Guo Wei


分析

根据要求将输入的整数原序输出两次,用","分隔
然后将输入的字符串原序输出两次,也用 ","分隔,并注意到

GoodCopy<int>()(a,a+m,a+m/2);GoodCopy<int>()(a,a+m,a+m/2);
Print(a+m/2,a+m/2 + m);

此处也要满足在输出一遍,可是他传入的参数是a+m/2那么说明这儿我们需要注意从a的地址开始复制的话,a+m的部分肯定有部分会被a+m/2给覆盖,那么我们只好从后面往前赋值才可解决该问题,所以总的解决方案是:

template <class T>
struct GoodCopy {
	operator()(T *a,T *ad,T * b){
		int flag = 0;
		for(T *temp = a;temp < ad;temp++){
			if(temp == b){
				flag = 1;
			}
		}
		while(flag == 0 && a != ad){
			*b = *a;
			b++;
			a++; 
		}
		if(flag == 1){
			for(T *temp = a;temp < ad;temp++,b++);
			--b;
			T * q = ad;
			-- q;
			for(;q != a;q--,b--)
				*b = *q;
			*b = *q;
		}
	} 
};

其中flag就是判断是否会出现覆盖现象,便于采取不同措施。

发布了205 篇原创文章 · 获赞 47 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44116998/article/details/104415086