zoukankan      html  css  js  c++  java
  • 模板类型的例子

    16.4 编写行为类似标准库find算法的模板。函数需要两个模板类型参数,一个表示函数的迭代器参数,另一个表示值的类型。使用你的函数在一个vector<int>和一个list<string>中查找给定值。

    #include<iostream>
    #include<vector>
    #include<list>
    #include<string>
    #include<algorithm>
    using namespace std;
    
    template <typename T1,typename T2>
    T1 find1(T1 begin,T1 end,const T2 &value)
    {
        if(find(begin,end,value)!=end)
            return find(begin,end,value);
        else
            return end;
    }
    int main()
    {
        vector<int> vec={1,3,4,5,6,7,8};
        list<string> lst={"w","a","m","fdhs","difi","aa"};
        cout<<*find1(vec.begin(),vec.end(),8)<<endl;
        cout<<find1(vec.begin(),vec.end(),8)-vec.begin()<<endl;
        cout<<*find1<list<string>::iterator,string>(lst.begin(),lst.end(),"a")<<endl;
        cout<<(find1<list<string>::iterator,string>(lst.begin(),lst.end(),"a")==lst.end()?"no exist":"exist")<<endl;
        return 0;
    }

    16.5print函数编写模板版本,它接受一个数组的引用,能处理任意大小、任意元素类型的数组。

    #include<iostream>
    #include<string>
    using namespace std;
    
    template<typename T,size_t n>
    void print(T (&arr)[n])
    {
        for(auto elem:arr)
            cout<<elem<<" ";
        cout<<endl;
    }
    
    int main()
    {
        int arr[10]={1,2,3,4,5,6,7,8,9,0};
        string str[5]={"a","b","c","d","e"};
        char ch[3]={'a','b','c'};
        print(arr);
        print(str);
        print(ch);
    }

    16.7 编写一个constexpr模板,返回给定数组的大小。

    #include<iostream>
    #include<string>
    using namespace std;
    
    template<typename T,size_t n>
    void print(T (&arr)[n])
    {
        for(auto elem:arr)
            cout<<elem<<" ";
        cout<<endl;
    }
    
    template<typename TT,size_t sz>
    constexpr size_t rtsize(TT (&)[sz])
    {
        return sz;
    }
    int main()
    {
        int arr[10]={1,2,3,4,5,6,7,8,9,0};
        string str[5]={"a","b","c","d","e"};
        char ch[3]={'a','b','c'};
        print(arr);
        print(str);
        print(ch);
        cout<<rtsize(arr)<<endl;
        cout<<rtsize(str)<<endl;
        cout<<rtsize(ch)<<endl;
    }
  • 相关阅读:
    移动端头部声明
    清除浮动绝招
    图片采用base64压缩,可以以字符串的形式传送base64给服务端转存为图片
    js cookie的封装和调用
    js 封装设计cookie
    div可编辑状态设置
    align使图片和文字居中
    布局如何做到自适应?
    Jmeter学习笔记四_压力测试
    Pycharm中配置Git版本管理
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3948086.html
Copyright © 2011-2022 走看看