C++笔记(class17.7)函数模板的本质

该代码示例展示了如何使用C++编写一个函数模板实现排序功能,可以应用于不同类型的数组,包括整型、短整型和字符串。函数接受一个指针、元素数量和一个布尔值,用于确定排序顺序。通过比较和交换元素实现升序或降序排列。
摘要由CSDN通过智能技术生成

实验一:函数内传入相同类型但大小不同的参数 

 

 

 项目练习:万能排序工具

 

#include <iostream>

void sort(int* ary, unsigned count, bool ispseq = true)
{
    int ls{};

    for (int i = 0; i < count; i++)
    {
        for (int j = i + 1; j < count; j++)
        {
            if ((ispseq)^(ary[i] < ary[j]))
            { 
                ls = ary[i];
                ary[i] = ary[j];
                ary[j] = ls;

            }
               
        }
    }
    
    for (int i = 0; i < count; i++)
    {
        std::cout << ary[i] << " ";
    }

    std::cout << std::endl;

}

template <typename T> 
void sort_temp(T* ary, unsigned count, bool IsPSeque)
{
    T ls{};
    for (int i = 0; i < count; i++)
    {
        for (int j = i + 1; j < count; j++)
        {
            if ((IsPSeque) ^ (ary[i] < ary[j]))
            {
                ls = ary[i];
                ary[i] = ary[j];
                ary[j] = ls;
            }
        }
    }

}
int main()
{
    int ary1[5]{ 45,34,65,67,232 };

    short ary2[5]{ 65,69,67,98,70 };

    std::string ary3[6]{ "abc","bcd","cde","fgh","ijk" };

    sort_temp(ary2, sizeof(ary2) / sizeof(short), true);
    for (auto x : ary2)std::cout << x<<" ";
    std::cout << std::endl;
    sort_temp(ary2, sizeof(ary2) / sizeof(short), false);
    for (auto x : ary2)std::cout << x<<" ";
    std::cout << std::endl;
    sort_temp(ary1, sizeof(ary1) / sizeof(int), true);
    for (auto x : ary1)std::cout << x << " ";
    std::cout << std::endl;
    sort_temp(ary1, sizeof(ary1) / sizeof(int), false);
    for (auto x : ary1)std::cout << x << " ";
    std::cout << std::endl;

    sort_temp(ary3, sizeof(ary3) / sizeof(std::string), true);
    for (auto x : ary3)std::cout << x << " ";
    std::cout << std::endl;

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值