模板类型的例子

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值