下面这两个程序第一个不能用指针做形参而第二个必须用,否则编译出错。
可以看出二者传入函数模板的参数都是数组指针,求大哥帮助
#include <iostream>
#include <string>
using namespace std;
//your code starts here
template <class T1, class T2>
T1 Filter( T1 s,T1 e, T1 s2, T2 op)
{
for(;s != e; ++s) {
if( op(*s)) {
* s2 = * s;
++ s2;
}
}
return s2;
}
//your code ends here
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 < p - as2; ++i)
cout << as2[i];
cout << endl;
int * p2 = Filter(a1,a1+5,a2,LargerThan2);
for(int i = 0;i < p2-a2; ++i)
cout << a2[i] << ",";
return 0;
}
#include <iostream>
#include <string>
using namespace std;
template <class T>
T SumArray(
// 在此处补充你的代码
T *a,T *b){
T sum=*a;
a++;
for(;a!=b;a++){
sum+=*a;
}
return sum;
}
int main() {
string array[4] = { "Tom","Jack","Mary","John"};
cout << SumArray(array,array+4) << endl;
int a[4] = { 1, 2, 3, 4}; //提示:1+2+3+4 = 10
cout << SumArray(a,a+4) << endl;
return 0;
}