这里的假设是我收到了很多值,我不想将它们存储在向量中。所以我想使用诸如升压蓄电池之类的东西。但是在文档中我找不到我想要的逻辑。
有没有办法让我拥有累加器,以便在调用时使用
5、10、12、15、27 它将输出 2(两个相邻值 10 和 12 之间的最小差异)。
我知道我可以自己保留最后一个变量,只需将 acc(current-last) 与 tag::min 一起使用,但如果可能的话,我更愿意将它留给库。
这里的假设是我收到了很多值,我不想将它们存储在向量中。所以我想使用诸如升压蓄电池之类的东西。但是在文档中我找不到我想要的逻辑。
有没有办法让我拥有累加器,以便在调用时使用
5、10、12、15、27 它将输出 2(两个相邻值 10 和 12 之间的最小差异)。
我知道我可以自己保留最后一个变量,只需将 acc(current-last) 与 tag::min 一起使用,但如果可能的话,我更愿意将它留给库。
不使用作为 Boost 一部分的累加器,但您可以编写自己的。
累加器本身看起来像这样。请注意,此版本仅正确处理递增的值序列,但不需要初始样本。如果你有不同的要求,你可以调整它。
namespace boost {
namespace accumulators {
namespace impl {
template<typename Sample>
struct min_adjacent_difference_accumulator
: accumulator_base
{
using result_type = Sample;
template<typename Args>
min_adjacent_difference_accumulator(Args const & args)
: last_seen(args[sample | std::optional<Sample>{}])
{
}
template<typename Args>
void operator ()(Args const & args)
{
Sample new_value = args[sample];
if (last_seen)
min_diff = std::min(min_diff, new_value - *last_seen);
last_seen = args[sample];
}
result_type result(dont_care) const
{
return min_diff;
}
private:
std::optional<Sample> last_seen;
Sample min_diff = std::numeric_limits<Sample>::max();
};
}}}
boost::accumulators::impl
文档中建议将其放入命名空间。
接下来,我们需要一个标签
namespace boost { namespace accumulators { namespace tag {
struct min_adjacent_difference
: depends_on<>
{
using impl = accumulators::impl::min_adjacent_difference_accumulator< mpl::_1 >;
};
}}}
和一个提取器
namespace boost {
namespace accumulators {
namespace extract {
inline extractor<tag::min_adjacent_difference> const min_adjacent_difference = {};
}
using extract::min_adjacent_difference;
}}
然后,您可以像使用 boost 提供的任何累加器一样使用它。您可以在编译器资源管理器上查看交互式版本。