Home > Net >  Providing an allocator for Boost's `cpp_dec_float_100`
Providing an allocator for Boost's `cpp_dec_float_100`

Time:10-04

I have a dataset stored in .root file format (from the CERN ROOT framework) as type cpp_dec_float_100 (from the boost::multiprecision library). This data is read into an std::vector<cpp_dec_float_100>. By default, cpp_dec_float_100 is unallocated. If I were to try to read this data into a vector as-is, an std::bad_alloc is thrown. So, I've taken the advice of the Boost docs and provided a generic allocator, which seems to solve the issue (and appears to cut the size the resulting vector in half).

Ultimately, I want to pass this vector as an argument to a function that I've written, which performs binary search on a vector to find the element of that vector closest to a given value:

#include <boost/multiprecision/cpp_dec_float.hpp>

using Mult_t = boost::multiprecision::cpp_dec_float<100, int, allocator<boost::multiprecision::number<boost::multiprecision::cpp_dec_float<100>>>>;

std::vector<Mult_t>::iterator search(std::vector<Mult_t> &vec, Mult_t value){

        auto it = lower_bound(vec.begin(), vec.end(), value);

        if(it != vec.begin()){

                if(abs(value - *(it - 1)) <  abs(value - *it)){
                        --it;
                }

        }

        return it;
}

I'm using the "alias" Mult_t as the alternative is a bit of a mouthful.

So, given the vector vec and the value val, this finds the element in vec nearest to val.


If I use the cpp_dec_float_100 type as-is (i.e. Mult_t = boost::multiprecision::cpp_dec_float_100), this works great. However, when I attempt to provide an allocator, I'm given the error:

In module 'std' imported from input_line_1:1:
/usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../include/c  /4.8.5/bits/stl_algobase.h:965:18: error: invalid operands to binary expression ('boost::multiprecision::backends::cpp_dec_float<100, int,
      std::allocator<boost::multiprecision::number<boost::multiprecision::backends::cpp_dec_float<100,
      int, void>, boost::multiprecision::expression_template_option::et_on> > >' and 'const
      boost::multiprecision::backends::cpp_dec_float<100, int,
      std::allocator<boost::multiprecision::number<boost::multiprecision::backends::cpp_dec_float<100,
      int, void>, boost::multiprecision::expression_template_option::et_on> > >')
          if (*__middle < __val)


I don't quite understand what's going on here, and the error message isn't terribly insightful.

CodePudding user response:

Your problem has nothing to do with allocator, just because cpp_dec_float<...> has no operator<(), only number<cpp_dec_float<...>> supports.

You should redefine your Mult_t as:

using namespace boost::multiprecision;
using Mult_t = number<
  cpp_dec_float<100, int, std::allocator<number<cpp_dec_float<100>>>>>;
  • Related