且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

模板类型的例子

更新时间:2022-08-22 08:15:16

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;
}