ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

函数模板(成长版)

2026/9/19 9:51:32 拓冰建站 浏览量
函数模板(成长版)

 与普通函数区别:1.多了个template<class T>;2.某些确定类型变不确定类型T

一:引子:

#include<iostream>
using namespace std;
template<typename T>
T Max(T a, T b)
{return a > b ? a : b;
}
int main()
{int x, y;double a, b;cin >> x >> y >> a >> b;cout << Max(a, b) << "\n" << Max(x, y);
}

结果: 

回文数判断

1.回文数1.回文数判断模板
模板:
#include <iostream>
#include <algorithm>
using namespace std;
template <typename T, size_t N>//size_t很多时候等价于int,但更安全,不会溢出
bool is_symmetric(T(&a)[N]) {//既可以接收数组,也可以接收字符串且传递了长度size_t i=0, j= N - 1;while (i <= j) {if (a[i] != a[j])return false;++i, --j;}return true;
} 测试:
int main() {int a[]{ 1, 2, 3, 4, 5, 4, 3, 2, 1 };cout << is_symmetric(a) << endl; //1cout << is_symmetric("aaaaaaaaaaaaaaaaa") << endl; //0
}