当前位置: 首页 > news >正文

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

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

代码

#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。

相关文章:

  • ARM 处理器平台 eMMC Flash 存储磨损测试示例
  • DeepSeek开源周,第三弹再次来袭,DeepGEMM
  • php 获取head参数
  • 小波变换背景预测matlab和python, pytorch样例
  • 《Operating System Concepts》阅读笔记:p147-p158
  • SkyWalking集成Kafka实现日志异步采集经验总结
  • Bsin-PaaS: 微前端设计
  • phpstudy安装教程dvwa靶场搭建教程
  • 掌握CSS弹性盒子:打造灵活且响应式的布局
  • 嵌入式linux学习之opencv交叉编译/移植并使用CmakeList编译demo
  • MySQL 中有哪些锁类型?MySQL 事务的二阶段提交是什么?MySQL 中如果发生死锁应该如何解决?
  • React 源码揭秘 | Effect更新流程
  • MySQL二进制日志(Binlog)是如何落盘
  • 【算法】哈希表详解
  • springboot 引入前端
  • 第2章_保护您的第一个应用程序
  • 待解决 leetcode71 简化路径 栈的应用
  • 【深入探索 Caffeine:Java 缓存利器】
  • 0.MySQL安装|卸载内置环境|配置官方yum源|安装mysql|登录mysql|设置配置文件(centos8.2)
  • docker 部署 rocketmq
  • lol网站怎么做/直通车关键词优化口诀
  • 做模具的都有什么网站/百度2022第三季度财报
  • 网站制作难度/seo导航站
  • 安徽两学一做网站/谷歌竞价推广教程
  • 网站建设中最重要的/百度长尾关键词挖掘工具
  • 东莞网站建设渠道/win7系统优化大师