1

I am looking for a convenient and optimized way to compare 2 valarrays for equality. I've seen that Boost somewhat supports that:

In /boost/accumulators/numeric/functional/valarray.hpp --

// for "promoting" a std::valarray<bool> to a bool, useful for
// comparing 2 valarrays for equality:
//   if(numeric::promote<bool>(a == b))
template<typename From>
struct promote<bool, From, void, std_valarray_tag>
: std::unary_function<From, bool> {
    bool operator ()(From &arr) const {
        BOOST_MPL_ASSERT((is_same<bool, typename From::value_type>));
        for(std::size_t i = 0, size = arr.size(); i != size; ++i) {
            if(!arr[i]) {
                return false;
            }
        }
        return true;
    }
};

The following trivial code runs with std::valarray:

#include <valarray>
typedef std::valarray<int>    valarray_t;

int main(void) {
    int arr_length = 30; int num_of_idx = 5;
    // initialize arr
    int* arr = new int[arr_length];
    for (int i=0; i<arr_length; i++)
        arr[i] = i;
    // Create a valarray of ints.
    valarray_t vi(arr, arr_length);
    std::valarray<bool> aaa = ( vi == vi );
}

How can I check whether aaa is all true by using Boost?

Thanks!

1 Answers1

3

The comment in your quoted code says exactly that:

bool allTrue = boost::numeric::promote<bool>(aaa);

Or just with C++11's standard library:

bool allTrue = std::all_of(begin(aaa), end(aaa), [](bool b){return b;});
Arne Mertz
  • 24,171
  • 3
  • 51
  • 90
  • Thanks for your quick reply Arne! The C++11 version works great -- thanks! The boost version compile but wouldn't link -- undefined reference to `boost::lazy_disable_if >, boost::mpl::if_ >, bool&, bool> >::type boost::numeric::promote >(std::valarray&)' collect2: error: ld returned 1 exit status Also, any idea which would translate to a more efficient code? – Liron Cohen Feb 12 '14 at 07:20
  • 1
    @LironCohen I think both versions should be roughly the same in terms of performance. For the linker error, you have to explicitly include `boost/accumulators/numeric/functional.hpp` *after* the `valarray.hpp`: http://coliru.stacked-crooked.com/a/56616329db200d43 – Arne Mertz Feb 12 '14 at 07:53