c++函数模板什么时候用指针参数

别看着我笑了 别看着我笑了 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面这两个程序第一个不能用指针做形参而第二个必须用,否则编译出错。
可以看出二者传入函数模板的参数都是数组指针,求大哥帮助
#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;
}
...全文

相关推荐

评论 1
收藏 已收藏
分享
返回顶部
别看着我笑了
C++ 语言 65,214 成员 250,514 内容