gpt4 book ai didi

c++ - 将递归变成循环

转载 作者:太空狗 更新时间:2023-10-29 20:36:59 25 4
gpt4 key购买 nike

我有一个未知类型 T,它可能是不可复制或可移动赋值的,一个函数 T op(const T &foo, Other bar) 计算和返回一个基于现有T 的新T,以及一个递归函数:

template<typename Iter, typename T>
T foldLeft(Iter first, Iter last, const T &z, std::function<T(T, Other)> op)
{
if (first == last) {
return z;
}
return foldLeft(std::next(first), last, op(z, *first), op);
}

编译器不能总是优化尾部调用,因为 T 可能有一个非平凡的析构函数。我试图用循环手动重写它,但无法弄清楚如何重新分配给 z

最佳答案

您可以执行以下操作,但限制很奇怪,使用 std::accumulate 似乎更简单

template<typename Iter, typename T, typename Fn>
T foldLeft(Iter first, Iter last, const T &z, Fn op)
{
std::aligned_storage_t<sizeof (T), alignof (T)> buf;
T* res = new (&buf) T(z);
for (auto it = first; it != last; ++it) {
auto&& res2 = op(res, it);
res->~T();
res = new (&buf) T(std::move(res2));
}
T final_res = *res;
res->~T();
return final_res;
}

请注意,它不是异常安全的。

关于c++ - 将递归变成循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36514544/

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