簡體   English   中英

升壓累加器是否支持計算相鄰值之間的最小差異?

[英]Do boost accumulators support the calculation of minimum difference between adjacent values?

這里的假設是我收到了很多值,我不想將它們存儲在向量中。 所以我想使用像升壓累加器這樣的東西。 但是在文檔中我找不到我想要的邏輯。

有沒有辦法讓我擁有累加器,以便在調用時

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 提供的任何累加器一樣使用它。 您可以在compiler explorer上查看交互式版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM