问题
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?
回答1:
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();
回答2:
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 bool
s 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.
来源:https://stackoverflow.com/questions/24628918/strange-c-compile-error-with-valarrays