我常常不能使用 std::for_each,因为我对特定元素的逻辑取决于它的当前索引。为此,我发明了一个仿函数类,它包装了主仿函数并将当前索引传递给它。理想情况下,我想将它与 lambda 表达式一起使用。我创建的类(class)安全有效吗?有没有更好的解决方案?我确实希望包装器的 operator () 返回 lambda 表达式的类型,但我想不通。另外,我应该为索引使用什么类型?我应该按值还是按引用将主仿函数存储在包装器中?
谢谢!
template<class FUNC>
class IndexFunctor
{
public:
typedef FUNC FUNC_T;
explicit IndexFunctor(const FUNC_T& func) : func(func), index(0) {}
// how can this return the return type of func?
template<class T>
void operator ()(T& param)
{
func(index++, param);
}
const FUNC_T& GetFunctor() const
{
return func;
}
int GetIndex() const
{
return index;
}
void SetIndex(int index)
{
this->index = index;
}
private:
FUNC_T func;
int index;
};
template<class FUNC>
IndexFunctor<FUNC> with_index(const FUNC& func)
{
return IndexFunctor<FUNC>(func);
}
void somefunc()
{
std::vector<int> v(10);
std::for_each(v.begin(), v.end(), with_index([](int index, int x){ std::cout << "[" << index << "]=" << x << std::endl; }));
}
最佳答案
这应该是安全的,尽管自己编写索引 for-each 相当简单。
template <typename TInputIterator, typename TFunc>
TFunc counted_for_each(TInputIterator first, TInputIterator last, TFunc func)
{
for (size_t i = 0; first != last; ++first)
{
func(i++, *first);
}
return func;
}
更少的代码并完成同样的事情。
关于c++ - 使 std::for_each 更有用——让仿函数知道当前索引是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17777032/