3

I have a strange compile error using valarrays in C++.

This is a stripped down version of my code:

#include <iostream>
#include <valarray>

using namespace std;

bool test(const int &x,const valarray<int> &a,const valarray<int> &b) {
    return a*x==b;
}

int main() {
    int a1[3]= {1,2,3};
    int b1[3]= {2,4,6};
    valarray<int> a(a1,3);
    valarray<int> b(b1,3);
    int x=2;
    cout<<test(x,a,b);
    return 0;
}

Expected behavior: outputs some variant of true or 1

The compile error (using g++):

main.cpp: In function ‘bool test(const int&, const std::valarray<int>&, const std::valarray<int>&)’:
main.cpp:7:14: error: cannot convert ‘std::_Expr<std::_BinClos<std::__equal_to, std::_Expr, std::_ValArray, std::_BinClos<std::__multiplies, std::_ValArray, std::_Constant, int, int>, int>, bool>’ to ‘bool’ in return
  return a*x==b;
              ^

What does this compile error mean, and how to fix it?

2 Answers2

8

The problem is that comparing valarrays with == does not return a bool, it returns std::valarray<bool>, doing the comparison element-wise.

If you want to compare them for equality, you can call min() on the result, since false < true:

return (a*x==b).min();
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Thank you! I initially thought that the `==` operator works the same way on `valarray`s and `vector`s (i.e. returns `bool`). Also, I was surprised that comparing `bool`s doesn't lead to compile errors. It's just a shame that there isn't an easier way to compare `valarray`s for equality. – Theemathas Chirananthavat Jul 08 '14 at 10:13
  • This is inefficient because it doesn't short-circuit. Is there a workaround? – a06e Jun 29 '15 at 21:39
5

What prevented you from reading the documentation? == does not work in this way for valarrays. It compares each element index-wise and returns a new valarray of bools containing each result.

Indeed, the entire purpose of valarrays is to enable quick and easy operations on an ordered set of values without having to resort to writing loops everywhere.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055