程序设计与算法(三)第07周测验
2021-02-11 21:18
阅读:630
TomJackMaryJohn 10
#include#include string> using namespace std; template class T> T SumArray(T *_start, T *_end) { // 在此处补充你的代码 T sum=*_start; while(++_start_end) { sum=sum+*_start; } return sum; } int main() { string array[4] = { "Tom","Jack","Mary","John"}; cout 4) endl; int a[4] = { 1, 2, 3, 4}; //提示:1+2+3+4 = 10 cout 4) endl; return 0; }
002:简单的foreach
编写MyForeach模板,使程序按要求输出 不得编写 MyForeach函数
#include#include using namespace std;
// 在此处补充你的代码
void Print(string s)
{
cout > m >> n) {
for(int i = 0;i > array[i];
for(int j = 0; j > a[j];
MyForeach(array,array+m,Print);
cout
输入多组数据
每组数据第一行是两个整数 m 和 n ,都不超过 50
第二行是m个不带空格的字符串
第三行是 n个整数输出对每组数据
第一行输出所有输入字符串连在一起的结果
第二行输出输入中的每个整数加1的结果样例输入
3 4
Tom Mike Jack
1 2 3 4
1 2
Peking
100 200
样例输出
TomMikeJack
2,3,4,5,
Peking
101,201,
#include
#include
#include string>
using namespace std;
// 在此处补充你的代码
template class T,class T1>
void MyForeach(T *_start ,T*_end,void f(T1 t ))
{
for (T* p=_start;p<_end>)
{
f(*p);
}
}
void Print(string s)
{
cout s;
}
void Inc(int & n)
{
++ n;
}
string array[100];
int a[100];
int main()
{
int m,n;
while(cin >> m >> n)
{
for(int i = 0; i i)
cin >> array[i];
for(int j = 0; j j)
cin >> a[j];
MyForeach(array,array+m,Print);
cout endl;
MyForeach(a,a+n,Inc);
for(int i = 0; i i)
cout ",";
cout endl;
}
return 0;
}
003:简单的Filter
#include
#include
using namespace std;
// 在此处补充你的代码
bool LargerThan2(int n)
{
return n > 2;
}
bool LongerThan3(string s)
{
return s.length() > 3;
}
string as1[5] = {"Tom","Mike","Jack","Ted","Lucy"};
string as2[5];
int a1[5] = { 1,2,3,4,5};
int a2[5];
int main() {
string * p = Filter(as1,as1+5,as2,LongerThan3);
for(int i = 0;i
输入无输出MikeJackLucy
3,4,5,样例输入
无
样例输出
MikeJackLucy
3,4,5,
#include
#include string>
using namespace std;
// 在此处补充你的代码
template class T,class T1,class T2>
T Filter( T s,T e,T s2, T1 f(T2))
{
while (s!=e){
if (f(*s)){
*s2++=*s++;
}
else ++s;
}
return s2;
}
bool LargerThan2(int n)
{
return n > 2;
}
bool LongerThan3(string s)
{
return s.length() > 3;
}
string as1[5] = {"Tom","Mike","Jack","Ted","Lucy"};
string as2[5];
int a1[5] = { 1,2,3,4,5};
int a2[5];
int main() {
string * p = Filter(as1,as1+5,as2,LongerThan3);
for(int i = 0;i i)
cout as2[i];
cout endl;
int * p2 = Filter(a1,a1+5,a2,LargerThan2);
for(int i = 0;i i)
cout ",";
return 0;
}
评论
亲,登录后才可以留言!