模板函数模板类入门

一 背景

因为做牛客的题目,做到一个关于模板的题目,感觉题目代码很好,也做对了,就想把题目代码记录下来。恰好平时模板用的少不是很熟,希望以此为开始。


二、模板函数示例代码

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

三、模板类

四、总结

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值