stl remove_if with class member function result

天大地大妈咪最大 提交于 2019-12-11 04:57:36

问题


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:


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));


来源:https://stackoverflow.com/questions/9922814/stl-remove-if-with-class-member-function-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!