一个行为类似标准库find算法的模板

发布于:2025-02-28 ⋅ 阅读:(17) ⋅ 点赞:(0)

函数需要两个模板类型参数,一个表示函数的迭代器参数,另一个表示值的类型。

代码

#include<iostream>
#include<string>
#include<vector>
#include<list>

using namespace std;

template <typename IterType,typename T>
IterType find(IterType begin,IterType end,const T &value)
{
    while(begin != end && *begin != value)
        begin++;
    return begin;
}

int main(int argc, char* argv[])
{
    vector<int> vi = {0,2,4,6,8,10};
    list<string> ls = {"Hello","World","!"};

    int to_find_int = 10;
    auto iter = find(vi.begin(),vi.end(),to_find_int);
    if(iter == vi.end())
        cout<<"can not find "<<to_find_int<<endl;
    else
        cout<<"found "<<to_find_int<<" at position "<<iter - vi.begin()<<endl;
    
    string to_find_str("mom");
    auto iter1 = find(ls.begin(),ls.end(),to_find_str);
    if(iter1 == ls.end())
        cout<<"can not find "<<to_find_str<<endl;
    else
        cout<<"found "<<to_find_str<<endl;
    return 0;
}

输出

found 10 at position 5
can not find mom

代码说明

用模板类型参数IterType表示迭代器类型,用T表示值的类型。

find算法接受两个类型为IterType的参数begin、end表示迭代器,和一个类型为T的参数value表示要查找的值。

函数遍历范围[begin, end)查找value,因此对IterType和T的要求是IterType必须支持++运算符和!=运算符,来实现遍历,并支持*运算符来获取元素值,且*运算的结果类型必须为T。

当对vector<int>调用find时,IterType被解析为vector<int>::iterator,T被解析为int;当对list<string>调用find时,IterType被解析为list<string>::iterator,T被解析为string。


网站公告

今日签到

点亮在社区的每一天
去签到