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

别看着我笑了 2020-01-29 12:27:40
下面这两个程序第一个不能用指针做形参而第二个必须用,否则编译出错。
可以看出二者传入函数模板的参数都是数组指针,求大哥帮助
#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;
}
...全文
102 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qybao 2020-01-29
  • 打赏
  • 举报
回复
第一个程序函数定义的参数不是指针形式,即T1 s这样的形式,第二个程序函数定义的参数是指针的形式,即T *a这样的形式,那调用函数的时候自然是根据参数定义的形式来传递参数了,跟模版没关系

64,683

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧