c++ template模板

本文介绍了C++中的函数模板和类模板。函数模板允许我们编写泛型代码,适用于不同数据类型,例如演示了使用模板实现的泡沫排序。类模板则用于创建可参数化的类,提供了链表模板的示例,并引用了相关学习资源。
摘要由CSDN通过智能技术生成

函式樣板

函数模板的声明形式如下:

template <class identifier> function_declaration;
template <typename identifier> function_declaration;
template < 樣板參數型態 樣板參數名 , …其他樣板參數 >
原型回傳型態 函式名稱(參數型態 原型參數名, ...)
{
程式碼;
} 

这里写图片描述

函式樣板:參數型態可用關鍵字 classtypename 表示泛用型態 (即任何型態);或是一個已宣告的資料型態,如int 與自定類。
原型中的參數型態若是已宣告的資料型態,則是一種特殊化的函式樣板。

#include <iostream>
using namespace std;
int Add(int a, int b)
{
return a + b;
}
template <class T>
T Add(T a, T b)
{
return a + b;
} 
int main()
{
int c1;
double c2;
c1 = Add(10, 20);
c2 = Add(10.3, 20.4);
return 0;
}

C++函式樣板寫一個泡沫排序法(BubbleSort):

#include <iostream>
#include <string>
using namespace std;

template <class T>
void BubbleSort(int n, T A[])
{
    T temp;
    int i, j;
    for (i = n - 1; i>1; i--)   //for(i=0; i<n-1; i++)
    {
        for (j = 0; j<i; j++)   //for(j=0; j<n-1; j++)
        {
            if (A[j] > A[j + 1])
            {
                temp = A[j];
                A[j] = A[j + 1];
                A[j + 1] = temp;
            }
        }
    }
}

template <class T>
void PrintArray(int n, T A[])
{
    int i;
    for (i = 0; i<n; i++)
        cout << A[i] << " ";
    cout << endl;
}

int main()
{
    int n = 5;
    int A1[5] = { 12,33,2,4,22 };
    double A2[5] = { 12.43, 12.33, 2.4 ,4.66 ,22.1 };
    char A3[5] = { 'G','B',
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值