一 背景
因为做牛客的题目,做到一个关于模板的题目,感觉题目代码很好,也做对了,就想把题目代码记录下来。恰好平时模板用的少不是很熟,希望以此为开始。
二、模板函数示例代码
2.1 第一次牛客上的例题
demo代码
#include <iostream>
using namespace std;
template <class T>
void S(T &x, T &y)
{
T temp;
temp = x;
x = y;
y = temp;
}
template <class T>
void SS(T A[], int n)
{
int min;
int i, j;
for (i=0; i<n-1; i++)
{
min=i;
for (j= i + 1; j<n; j++)
if (A[j]<A[min])
min=j;
S(A[i], A[min]);
}
}
int main()
{
int array1[] = {7,2,76,23,11, 9};
SS<int>(array1, 6);
for(int i = 0; i < 6; i++)
{
printf("%d ", array1[i]);
}
char array2[] = "helloworld";
SS<char>(array2, strlen(array2));
for(int i = 0; i < strlen(array2); i++)
{
printf("%c ", array2[i]);
}
}
//2 7 9 11 23 76
//d e h l l l o o r w
2.2 后面又看到的模板函数
记录一下
//main.cpp文件
#include <iostream>
#include "log.h"
using namespace std;
int main() {
std::cout << "Hello, World!" << std::endl;
DBGprint("test DBGprint!\n");
PrintInfoMsg("this is a test", "hello world");
PrintInfoMsg(3, 7);
//也可以写成下面这种形式
PrintInfoMsg<string, string>("this is second test", "happy new year");
return 0;
}
//预测结果是10
//log.h文件
#ifndef LOG_H
#define LOG_H
#include <iostream>
using namespace std;
#ifdef _DEBUG
#define DBGprint(...) printf(__VA_ARGS__)
#else
#define DBGprint(...) //这边没哟定义函数,意味着没有定义,printf(__VA_ARGS__)函数会灰掉不执行
#endif
template <typename T1, typename T2>
void PrintInfoMsg(const T1 &msg1, const T2& msg2)
{
std::cout << msg1 << " " << msg2 << std::endl;
}
#endif
打印结果
D:\AppData\CLion\testProj\cmake-build-debug\hello.exe
Hello, World!
1
2
3
4
5
6
7
8
9
10
test DBGprint!
this is a test hello world
3 7
this is second test happy new year