gpt4 book ai didi

c++ - 将 for_each 和 boost::bind 与指针 vector 一起使用

转载 作者:可可西里 更新时间:2023-11-01 16:29:28 30 4
gpt4 key购买 nike

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

例子:

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

我可以创建一个带指针的脏小包装器,但我认为必须有更好的方法吗?

最佳答案

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

这将在其 operator* 中两次取消引用适配的迭代器。

关于c++ - 将 for_each 和 boost::bind 与指针 vector 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2413786/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com