stl remove_if with class member function result

2019-07-25 08:43发布

I have a object container, list; and class Foo have a member function id() return an integer identifier. Now I want to use stl algorithm remove_if to remove some objects whose id is less than a value. I don't want to provide a function for id compare, If it is possible for me to write one line code with STL but boost to implement it.

class Foo{
public:
  unsigned id() const {return id_;}
  ...
private:
  unsigned id_
  ...
};
list<Foo> foo_list;
std::remove_if(foo_list.begin(), foo_list.end(), ???);

If STL can do this with only std::bind2nd, stl::less(), std::mem_fun_ref() or other stl functions.

1条回答
Evening l夕情丶
2楼-- · 2019-07-25 09:26

Yes, that is possible to achieve without lambdas, if you agree to change the interface of Foo a little bit.

class Foo
  {
public:
  Foo(unsigned id)
    : id_(id) {}
  bool is_equal(unsigned id) const
    { return id_ == id; }
private:
  unsigned id_;
  };

typedef list<Foo> FooList;

FooList foo_list;
foo_list.push_back(Foo(1));
foo_list.push_back(Foo(2));

unsigned to_remove = 1;
foo_list.remove_if(std::bind2nd(std::mem_fun_ref(&Foo::is_equal), to_remove));
查看更多
登录 后发表回答