模板類型的例子

來源:互聯網
上載者:User

標籤:style   blog   color   os   使用   io   ar   for   div   

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

 

模板類型的例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.