C++ 模板函数copy 001:goodcopy

001:goodcopy

描述
编写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, 

解题
实现copy功能;
重载(),即构建一个函数对象;
因为本题样例中正序赋值会覆盖自身,故使用倒序赋值即可通过;

void operator()(T *s, T *e, T *n){       //重载() 
	while(s!=e){                      //倒序赋值 
		n[e-s-1]=s[e-s-1];
		--e;
	}
}

当然,虽然上面的方法可以通过本题的提交,
但是更完备的方案是要判断给定的参数是否会覆盖自身,再决定正序copy还是倒序copy;
因为如果x的末位在s和e之间的话,则需要正序赋值;
而x的首位在s和e之间的话,需要倒序赋值;

	void operator()(T* s,T* e,T* x) 
	{ 
		bool backward = false;         //判断是否要反向赋值 
		T * tmp;
		for(tmp = s;tmp!= e; ++tmp) {
			if( tmp == x ) {            //x为s-e中间的一段 
				backward = true;        //需要倒序copy 
				break;
			}
		}
		if( !backward) {              //正向copy 
			for(; s != e; ++s,++x)
				* x = * s;
		}
		else {                
			T * p = x;              //p指向x头部 
			for(tmp = s; tmp != e; ++tmp,++p);     //p指向x[e-s]         
			--p;                                 //p指向x[e-s-1] 
			T * q = e;               
			-- q;                             //q指向e-1 
			for(; q != s; --q, --p)           //从后往前赋值 
				* p = * q;            
			*p = * q;                        //最后的0索引赋值 
		}
	}
发布了77 篇原创文章 · 获赞 3 · 访问量 3044

猜你喜欢

转载自blog.csdn.net/BLUEsang/article/details/105212331
今日推荐