使用for_each和boost :: bind与指针的向量 [英] Using for_each and boost::bind with a vector of pointers

查看:183
本文介绍了使用for_each和boost :: bind与指针的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指针的向量。我想为每个元素调用一个函数,但该函数需要一个参考。是否有简单的方法来取消引用元素?



示例:

  MyClass :: ReferenceFn(Element& e){...} 

MyClass :: PointerFn(Element * e){...}

MyClass :: Function ()
{
std :: vector<元素*>元素;
//添加一些元素...

//这是可行的,因为参数是一个指针类型
std :: for_each(elements.begin(),elements.end (),
boost :: bind(& MyClass :: PointerFn,boost :: ref(* this),_1));

//这个失败(编译器错误),因为参数是一个引用类型
std :: for_each(elements.begin(),elements.end(),
boost :: bind(& MyClass :: ReferenceFn,boost :: ref(* this),_1));
}

我可以创建一个脏的小包装,

你可以使用 boost :: indirect_iterator c>:

  std :: for_each(boost :: make_indirect_iterator(elements.begin()),
boost: :make_indirect_iterator(elements.end()),
boost :: bind(& MyClass :: ReferenceFn,boost :: ref(* this),_1)

这将在运算符*


I have a vector of pointers. I would like to call a function for every element, but that function takes a reference. Is there a simple way to dereference the elements?

Example:

MyClass::ReferenceFn( Element & e ) { ... }

MyClass::PointerFn( Element * e ) { ... }

MyClass::Function()
{
    std::vector< Element * > elements;
    // add some elements...

    // This works, as the argument is a pointer type
    std::for_each( elements.begin(), elements.end(),
                   boost::bind( &MyClass::PointerFn, boost::ref(*this), _1 ) );

    // This fails (compiler error), as the argument is a reference type
    std::for_each( elements.begin(), elements.end(),
                   boost::bind( &MyClass::ReferenceFn, boost::ref(*this), _1 ) );
}

I could create a dirty little wrapper that takes a pointer, but I figured there had to be a better way?

解决方案

You could use boost::indirect_iterator:

std::for_each( boost::make_indirect_iterator(elements.begin()), 
               boost::make_indirect_iterator(elements.end()),
               boost::bind( &MyClass::ReferenceFn, boost::ref(*this), _1 ) );

That will dereference the adapted iterator twice in its operator*.

这篇关于使用for_each和boost :: bind与指针的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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