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

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

问题描述

我有指针的载体。我想呼吁每个元素的功能,但该功能需要一个参考。有没有一种简单的方法来解引用的元素?

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?

例如:

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?

推荐答案

您可以使用的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 ) );

这将间接引用其运算符*两次改编的迭代器

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

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