• 模板类型的例子


    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;
    }
  • 相关阅读:
    java 单元测试 No tests were found 和 org.junit.platform.commons.JUnitException: TestEngine with ID 'junit-jupiter' failed to discover tests
    Cesium 各种坐标转换
    windows express + https ssl 证书申请
    layui数据表格跨行自动合并
    mui中的遍历each()
    点击按钮,回到页面顶部的5种写法
    html中a标签中实现点击事件
    @-webkit-keyframes 动画 css3
    在手机上调试H5页面
    SQL Server 按某一字段分组取最大(小)值所在行的数据
  • 原文地址:https://www.cnblogs.com/wuchanming/p/3948086.html
Copyright © 2020-2023  润新知