c++函数模板什么时候用指针参数
下面这两个程序第一个不能用指针做形参而第二个必须用,否则编译出错。
可以看出二者传入函数模板的参数都是数组指针,求大哥帮助
#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;
}
可以看出二者传入函数模板的参数都是数组指针,求大哥帮助

#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;
}
...全文
相关推荐
Cpp Primer Plus第6版源码
**函数与函数模板**:C++支持函数作为参数传递和返回,以及函数指针。函数模板则允许编写泛化的函数,可以适用于不同类型的参数。源码中会展示如何利用这些特性编写可复用的代码。8.
函数模板.cpp
模板参数可以用尖括号<>括起来,并且可以是类型参数或非类型参数。类型参数通常用字母T表示,而非类型参数则用于指定整型或指针类型等具体值。
CPP132:CPP132的笔记和作业回购
**指针**:掌握指针的概念和操作,包括指针的声明、赋值、解引用和指针作为函数参数。6. **内存管理**:理解动态内存分配(new/delete)和智能指针,避免内存泄漏。7.
c++ 模板 类 代码 参考
例如,`template <typename T> T max(T a, T b)` 是一个函数模板,它可以接受任何类型(T)的参数并返回最大值。
cPP.cpp.tar.gz_6 Plus_?CPP Primer Plus 6
9. "3.12.cpp":可能探讨了函数模板和泛型编程,这是C++中实现代码重用的重要方式。


