奇怪的C ++编译错误valarrays [英] Strange C++ compile error with valarrays
本文介绍了奇怪的C ++编译错误valarrays的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C ++中使用valarrays有一个奇怪的编译错误。
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;
}
$ b $ p
预期行为:输出 true
或
1
编译错误(使用g ++):
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?
推荐答案
问题是比较valarrays与 ==
不会返回 bool
,它返回 std :: valarray< bool>
,比较元素。
The problem is that comparing valarrays with ==
does not return a bool
, it returns std::valarray<bool>
, doing the comparison element-wise.
如果你想比较它们的相等性,可以在结果上调用 min()
,因为 false< true
:
If you want to compare them for equality, you can call min()
on the result, since false < true
:
return (a*x==b).min();
这篇关于奇怪的C ++编译错误valarrays的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文