百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

C++ STL find和find_if算法与bind、lambda组合使用

ztj100 2025-01-03 20:47 20 浏览 0 评论

  • std::find
  • std::find_if
  • std::bind
  • std::distance
  • lambda
  • 直接上代码,使用std::find、std::find_if来搜索匹配,代码确实比for循环变少和更好看了,但是时间复杂度还是O(n),见下文。

    Bash
    #include <algorithm>
    #include <functional>
    #include <iostream>
    #include <string>
    #include <vector>
    
    class Item {
     private:
      int mId;
      std::string mName;
    
     public:
      Item(int id, std::string name) : mId(id), mName(name) {}
    
      std::string getName() const { return mName; }
    
      int getId() const { return mId; }
    
      bool operator==(const Item& obj2) const {
        return (this->getName().compare(obj2.getName()) == 0) &&
               (this->getId() == obj2.getId());
      }
    
      static bool Compare(const Item& obj1, const Item& obj2) {
        return (obj1.getName().compare(obj2.getName()) == 0) &&
               (obj1.getId() == obj2.getId());
      }
    };
    
    #define log(obj, pos)                                                      \
      do {                                                                     \
        if (it != sItemList.end()) {                                           \
          std::cout << "Found obj " << obj.getName() << ", id:" << it->getId() \
                    << ",name: " << it->getName() << ",position:" << pos       \
                    << std::endl;                                              \
        } else {                                                               \
          std::cout << "Not Found obj" << std::endl;                           \
        }                                                                      \
      } while (false)
    
    std::vector<Item> sItemList = {{0, "A"}, {1, "B"}, {2, "C"}, {3, "D"}, {4, "E"},
                                   {5, "E"}, {6, "G"}, {7, "H"}, {1, "B"}};
    
    int main() {
      Item obj1(1, "B");
      Item obj2(8, "I");
      Item obj3(5, "E");
      Item obj4(7, "H");
    
      std::cout << "obj1 is equal obj1 : " << (obj1 == obj1) << std::endl;
      std::cout << "obj1 is equal obj2 : " << (obj1 == obj2) << std::endl;
    
      // 1. std::find 类重载运算符==,使用默认的比较函数查找等于的项
      std::vector<Item>::iterator it =
          std::find(sItemList.begin(), sItemList.end(), obj1);
      log(obj1, std::distance(sItemList.begin(), it));
    
      // 2. std::find 类重载运算符==,使用默认的比较函数d方向查找等于的项
      std::vector<Item>::reverse_iterator rit =
          std::find(sItemList.rbegin(), sItemList.rend(), obj1);
      log(obj1, (sItemList.size() - std::distance(sItemList.rbegin(), rit)));
    
      // 3. std::find_if 使用自定义的函数查找符合要求的项
      it = std::find_if(sItemList.begin(), sItemList.end(),
                        std::bind(Item::Compare, std::placeholders::_1, obj3));
      log(obj3, std::distance(sItemList.begin(), it));
    
      // 4. std::find_if使用 lambda 表达式查找符合的项
      it = std::find_if(
          sItemList.begin(), sItemList.end(),
          [&obj4](Item const& obj) { return Item::Compare(obj, obj4); });
      log(obj4, std::distance(sItemList.begin(), it));
    
      return 0;
    }

    编译运行结果:

    Bash
    $ g++ std_find.cpp  --std=c++11;./a.out
    obj1 is equal obj1 : 1
    obj1 is equal obj2 : 0
    Found obj B, id:1,name: B,position:1
    Found obj B, id:1,name: B,position:9
    Found obj E, id:5,name: E,position:5
    Found obj H, id:7,name: H,position:7


    std::find算法的行为如下所示,时间复杂度为O(n):

    template<class InputIterator, class T>
      InputIterator find (InputIterator first, InputIterator last, const T& val)
    {
      while (first!=last) {
        if (*first==val) return first;
        ++first;
      }
      return last;
    }

    相关推荐

    10条军规:电商API从数据泄露到高可用的全链路防护

    电商API接口避坑指南:数据安全、版本兼容与成本控制的10个教训在电商行业数字化转型中,API接口已成为连接平台、商家、用户与第三方服务的核心枢纽。然而,从数据泄露到版本冲突,从成本超支到系统崩溃,A...

    Python 文件处理在实际项目中的困难与应对策略

    在Python项目开发,文件处理是一项基础且关键的任务。然而,在实际项目中,Python文件处理往往会面临各种各样的困难和挑战,从文件格式兼容性、编码问题,到性能瓶颈、并发访问冲突等。本文将深入...

    The Future of Manufacturing with Custom CNC Parts

    ThefutureofmanufacturingisincreasinglybeingshapedbytheintegrationofcustomCNC(ComputerNumericalContro...

    Innovative Solutions in Custom CNC Machining

    Inrecentyears,thelandscapeofcustomCNCmachininghasevolvedrapidly,drivenbyincreasingdemandsforprecisio...

    C#.NET serilog 详解(c# repository)

    简介Serilog是...

    Custom CNC Machining for Small Batch Production

    Inmodernmanufacturing,producingsmallbatchesofcustomizedpartshasbecomeanincreasinglycommondemandacros...

    Custom CNC Machining for Customized Solutions

    Thedemandforcustomizedsolutionsinmanufacturinghasgrownsignificantly,drivenbydiverseindustryneedsandt...

    Revolutionizing Manufacturing with Custom CNC Parts

    Understandinghowmanufacturingisevolving,especiallythroughtheuseofcustomCNCparts,canseemcomplex.Thisa...

    Breaking Boundaries with Custom CNC Parts

    BreakingboundarieswithcustomCNCpartsinvolvesexploringhowadvancedmanufacturingtechniquesaretransformi...

    Custom CNC Parts for Aerospace Industry

    Intherealmofaerospacemanufacturing,precisionandreliabilityareparamount.Thecomponentsthatmakeupaircra...

    Cnc machining for custom parts and components

    UnderstandingCNCmachiningforcustompartsandcomponentsinvolvesexploringitsprocesses,advantages,andcomm...

    洞察宇宙(十八):深入理解C语言内存管理

    分享乐趣,传播快乐,增长见识,留下美好。亲爱的您,这里是LearingYard学苑!今天小编为大家带来“深入理解C语言内存管理”...

    The Art of Crafting Custom CNC Parts

    UnderstandingtheprocessofcreatingcustomCNCpartscanoftenbeconfusingforbeginnersandevensomeexperienced...

    Tailored Custom CNC Solutions for Automotive

    Intheautomotiveindustry,precisionandefficiencyarecrucialforproducinghigh-qualityvehiclecomponents.Ta...

    关于WEB服务器(.NET)一些经验累积(一)

    以前做过技术支持,把一些遇到的问题累积保存起来,现在发出了。1.问题:未能加载文件或程序集“System.EnterpriseServices.Wrapper.dll”或它的某一个依赖项。拒绝访问。解...

    取消回复欢迎 发表评论: