stl remove_if与类成员函数结果 [英] stl remove_if with class member function result

查看:112
本文介绍了stl remove_if与类成员函数结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象容器,列表;和Foo类具有成员函数id()返回整数标识符。
现在,我想使用stl算法remove_if删除一些ID小于值的对象。
我不想提供一个用于进行ID比较的功能,如果我可以用STL编写一行代码,但可以提高实现的可能性。

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(), ???);

如果STL仅使用std :: bind2nd,stl :: less(),std: :mem_fun_ref()或其他stl函数。

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

推荐答案

是的,如果您同意更改 Foo 的界面。

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

这篇关于stl remove_if与类成员函数结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆