【问题标题】:find int inside struct with find_if for std::list with structs使用 find_if 在结构内查找 int 用于带有结构的 std::list
【发布时间】:2010-10-22 11:48:23
【问题描述】:

如果列表包含结构,我如何将 find_if 与 std::list 一起使用?我的第一次伪代码尝试如下所示:

typename std::list<Event>::iterator found = 
    find_if(cal.begin(), cal.last(), predicate); 

这里的问题是谓词在列表中不是直接可见的,而是在event.object.return_number() 中。我想如何引用嵌套在结构内并需要访问 get 方法的 int。

【问题讨论】:

    标签: c++ list stl


    【解决方案1】:

    你可以使用仿函数类(类似于函数,但允许你拥有状态,比如配置):

    class Predicate
    {
    public:
        Predicate(int x) : x(x) {}
        bool operator() (const Cal &cal) const { return cal.getter() == x; }
    private:
        const int x;
    };
    
    std::find_if(cal.begin(), cal.end(), Predicate(x));
    

    【讨论】:

    • 谢谢,这很可能是我想要的。虽然我只是想在我的 Event 结构中重载 operator== ,但您对此有何看法?然后我可以使用事件作为谓词吗?
    • @foo:可能是个坏主意!仅仅看它并不清楚e == 3 在做什么。运算符重载应保留在含义明确的情况下。
    • 没关系,我使用了仿函数并且效果很好。再次感谢。
    【解决方案2】:

    在您的编译器可能已经部分实现的 C++0x 中,您可以执行以下操作:

    find_if(cal.begin(), cal.last(), [&](const Event& e) 
            { 
                return e.object.return_number() == value_to_find;
            });
    

    【讨论】:

    • 谢谢,我认为在这种情况下,出于兼容性原因,我需要远离 C++0x。不过我会记住这一点。
    【解决方案3】:

    你这样设置你的谓词:

    struct IsEventObjectReturnNumber
    {
       int num;
       explicit IsEventObjectReturnNumber( int n ) : num( n ) {}
    
       bool operator()(const Event & event ) const
       {
          return event.object.return_number() == num;
       }
    };
    
    std::list<Event>::iterator = std::find_if(cal.begin(), cal.end(), IsEventObjectReturnNumber(x));
    

    【讨论】:

    • 谢谢,我最终使用了我想要的函子。
    【解决方案4】:

    (不是那么简单,但是)最简单的方法(在没有 C++11 的情况下)是自定义比较器:

    struct CompareMyStruct {
        int n_;
        CompareMyStruct(int n) : n_(n) { }
        bool operator()(const Event& a) const {
            return a.object.return_number() == n_;
        }
    };
    
    typename std::list<Event>::iterator found =
        find_if(cal.begin(), cal.last(), CompareMyStruct(123));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-01
      • 2010-12-09
      • 1970-01-01
      • 2021-07-14
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 2020-09-01
      相关资源
      最近更新 更多