【问题描述】
理解主函数代码,设计一个将两个一维数组中同下标元素求和保存到第三个数组中的函数模板。而对两个字符串求和则要求实现两个字符串的连接并保存到第三个字符串中。编程实现上述功能并使程序正确运行。说明:若
int x[3] = { 2,4,6 };int y[3] = { 1,2,3};
x和y求和保存到z,则:z[3] = { 3,6,9 };
char c[]=“abc”,d[]=“xy”;
c和d求和保存到str,str中就是“abcxy”。
/*理解主函数代码,设计一个将两个一维数组中同下标元素求和保存到第三个数组中的函数模板。而对两个字符串求和则要求实现两个字符串的连接并保存到第三个字符串中。编程实现上述功能并使程序正确运行。说明:若
int x[3] = { 2,4,6 };int y[3] = { 1,2,3};
x和y求和保存到z,则:z[3] = { 3,6,9 };
char c[]=“abc”,d[]=“xy”;
c和d求和保存到str,str中就是“abcxy”。*/
#include <iostream>
#include <cstring>
using namespace std;
template<typename T, int N>
void Add(T x[], T y[], T z[]) {
for (int i = 0; i < N; i++) {
z[i] = x[i] + y[i];
}
}
template<typename T>
void Add(T c[], T d[], T str[]) {
strcat(c, d);
strcpy(str, c);
}
int main()
{
const int N = 5;
int x[N] = { 2,-4,6,8,0},y[N], z[N] = {0};
char c[] = "Hello,", d[100] ;
for (int i(0); i < N; i++)
cin >> *(y + i);
while (cin.get() != '\n');
cin.getline(d, 100);
Add<int, N>(x, y, z);
for (int i(0); i < N; i++)
cout<<z[i]<< " ";
cout<<endl;
char* pc = new char[strlen(c) + strlen(d) + 1];
Add(c, d, pc);
cout << pc << endl;
delete[]pc;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
template<typename T, int N>
void Add(T x[], T y[], T z[]) {
for (int i = 0; i < N; i++) {
z[i] = x[i] + y[i];
}
}
template<typename T>
void Add(T c[], T d[], T str[]) {
strcpy(str, c);
strcat(str, d);
}
int main()
{
const int N = 5;
int x[N] = { 2,-4,6,8,0},y[N], z[N] = {0};
char c[] = "Hello,", d[100] ;
for (int i(0); i < N; i++)
cin >> *(y + i);
while (cin.get() != '\n');
cin.getline(d, 100);
Add<int, N>(x, y, z);
for (int i(0); i < N; i++)
cout<<z[i]<< " ";
cout<<endl;
char* pc = new char[strlen(c) + strlen(d) + 1];
Add(c, d, pc);
cout << pc << endl;
delete[]pc;
return 0;
}