Is it possible to use boost accumulators with vectors?

后端 未结 3 2020
臣服心动
臣服心动 2020-12-15 23:29

I wanted to use boost accumulators to calculate statistics of a variable that is a vector. Is there a simple way to do this. I think it\'s not possible to use the dumbest th

3条回答
  •  不思量自难忘°
    2020-12-15 23:53

    I've looked into your question a bit, and it seems to me that Boost.Accumulators already provides support for std::vector. Here is what I could find in a section of the user's guide :

    Another example where the Numeric Operators Sub-Library is useful is when a type does not define the operator overloads required to use it for some statistical calculations. For instance, std::vector<> does not overload any arithmetic operators, yet it may be useful to use std::vector<> as a sample or variate type. The Numeric Operators Sub-Library defines the necessary operator overloads in the boost::numeric::operators namespace, which is brought into scope by the Accumulators Framework with a using directive.

    Indeed, after verification, the file boost/accumulators/numeric/functional/vector.hpp does contain the necessary operators for the 'naive' solution to work.

    I believe you should try :

    • Including either
      • boost/accumulators/numeric/functional/vector.hpp before any other accumulators header
      • boost/accumulators/numeric/functional.hpp while defining BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT
    • Bringing the operators into scope with a using namespace boost::numeric::operators;.

    There's only one last detail left : execution will break at runtime because the initial accumulated value is default-constructed, and an assertion will occur when trying to add a vector of size n to an empty vector. For this, it seems you should initialize the accumulator with (where n is the number of elements in your vector) :

    accumulator_set, stats > acc(std::vector(n));
    

    I tried the following code, mean gives me a std::vector of size 2 :

    int main()
    {
        accumulator_set, stats > acc(std::vector(2));
    
        const std::vector v1 = boost::assign::list_of(1.)(2.);
        const std::vector v2 = boost::assign::list_of(2.)(3.);
        const std::vector v3 = boost::assign::list_of(3.)(4.);
        acc(v1);
        acc(v2);
        acc(v3);
    
        const std::vector &meanVector = mean(acc);
    }
    

    I believe this is what you wanted ?

提交回复
热议问题