zoukankan      html  css  js  c++  java
  • C++入门经典-例9.2-重载函数模板,求出字符串的最小值

    1:整形数和实型数编译器可以直接进行比较,所以使用函数模板后也可以直接进行比较,但如果是字符指针指向的字符串该如何处理呢?这时可以通过重载函数模板来实现。通常字符串需要库函数来进行比较,通过重载函数模板实现字符串的比较。

    2:代码如下:

    // 9.2.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <iostream >
    #include <string >
    using namespace std;
    template<class Type>
    Type min(Type& a,Type& b)            //定义函数模板
    {
        if(a < b)
            return a;
        else
            return b;
    }
    char  min(char  a,char b)        //重载函数模板
    {
        if(strcmp(&a,&b))
            return b;
        else 
            return a;
    }
    void main ()
    {
        cout << "最小值:" << min(10,1) << endl;
        cout << "最小值:" << min('a','b') << endl;
        string s1 = "hi";
        string s2 = "mr";
        cout << "最小值:" << min(s1,s2) << endl;
    }
    View Code

    运行结果:

        在重载的函数模板min的实现中,使用strcmp库函数来完成字符串的比较,此时使用min函数可以比较整形数据、实型数据、字符数据和字符串数据。

  • 相关阅读:
    C. Karen and Game
    BZOJ2134: 单选错位
    BZOJ3562: [SHOI2014]神奇化合物
    BZOJ1084: [SCOI2005]最大子矩阵
    BZOJ5039: [Jsoi2014]序列维护
    BZOJ1798: [Ahoi2009]Seq 维护序列seq
    BZOJ3932: [CQOI2015]任务查询系统
    BZOJ3339: Rmq Problem
    BZOJ3585: mex
    BZOJ4196: [Noi2015]软件包管理器
  • 原文地址:https://www.cnblogs.com/lovemi93/p/7576997.html
Copyright © 2011-2022 走看看