我在使用C++的valarrays时遇到了一个奇怪的编译错误。
这是我的代码的简化版本:
#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;
}
预期行为:输出true
或1
的某个变体。
编译错误(使用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;
^
这个编译错误的意思是什么,如何修复它?
==
运算符在valarray
和vector
上的工作方式相同(即返回bool
)。此外,我很惊讶比较bool
不会导致编译错误。遗憾的是,没有更简单的方法来比较valarray
的相等性。 - Theemathas Chirananthavat