zoukankan      html  css  js  c++  java
  • STL(1)——查找函数find的使用

    使用list, vector 等这些标准库的类,查找是比较常用的功能,但是这些类没有提供find函数,因为对于自定义类型,它不知道如何去比较两个类型。

    http://www.cppreference.com/wiki/container/list/start

    但是STL提供了一种通用的查找函数find(iterator it0,iterator it1,target),下面介绍如何使用这个查找函数。

    // 定义一个简单的数据结构Inst.
    class Inst{
    public:
    Inst(
    string nm,int val){
    name
    = nm;
    value
    = val;
    }
    // 之前这里有个分号,并不应该出现的,谢谢提醒
    string Name() const{
    return name;
    }
    int Value() const{
    return value;
    }
      
    private:
    string name;
    int value;
    };
    // 定义比较函数,重载==运算符。
    // name 和 value 都一样, 则 实例一样
    booloperator==(const Inst &a, const Inst &b){
    return (a.Name()==b.Name() && a.Value()==b.Value());
    }

    // name 一样, 则 实例一样
    booloperator==(const Inst &a, conststring name){
    return (a.Name()==name);
    }

    测试如下,

    list<Inst> elist;
    Inst p1(
    "abc",3);
    Inst p2(
    "abcdef",6);

    list
    <Inst>::iterator it;
    // find 需要包含头文件 <algorithm>
    it = std::find(elist.begin(),elist.end(),p2);
    if(it!=elist.end())
    cout
    << (*it).Value() << endl;
    string name ="abc";
    it
    = std::find(elist.begin(),elist.end(),name);
    if(it!=elist.end())
    cout
    << (*it).Value() << endl;

    但是如果list保存指针,如下,

    list<Inst*> elist;
    Inst
    * p1 =new Inst("abc",3);
    Inst
    * p2 = New Inst("abcdef",6);
    list
    <Inst*>::iterator it;
    it
    = std::find(elist.begin(),elist.end(),p2);
    if(it!=elist.end())
    cout
    << (*it)->Value() << endl;
    string name ="abc";
    it
    = std::find(elist.begin(),elist.end(),name);
    if(it!=elist.end())
    cout
    << (*it)->Value() << endl;

    那么比较函数就需要做一些修改,如下,

    booloperator==(const Inst* a,const Inst* b){
    return (a->Name()==b->Name() && a->Value()==b->Value());
    }
    booloperator==(const Inst* a, conststring nm){
    return (a->Name()==nm);
    }

    在学习STL过程中,如果有错误的地方,还请各位指正,谢谢!

  • 相关阅读:
    说说我当初是如何学Linux的
    案例八:shell自动化管理账本脚本
    案例七:shell实现开机自动播放挂载本地yum仓库程序
    案例六:shell脚本监控httpd服务80端口状态
    案例五:shell脚本实现定时监控http服务的运行状态
    案例四:Shell脚本生成随机密码
    案例三:shell统计ip访问情况并分析访问日志
    案例二:shell脚本获取当前日期和时间及磁盘使情况
    案例一:shell脚本指定日期减去一天
    Linux:保证数据安全落盘
  • 原文地址:https://www.cnblogs.com/Frandy/p/STL_Find_List.html
Copyright © 2011-2022 走看看