3

我在 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;
              ^

这个编译错误是什么意思,以及如何修复它?

4

2 回答 2

8

问题是比较 valarrays==不返回 a bool,它返回std::valarray<bool>,按元素进行比较。

如果要比较它们是否相等,可以调用min()结果,因为false < true

return (a*x==b).min();
于 2014-07-08T10:03:02.197 回答
4

是什么阻止了您阅读文档?==对 valarrays 不起作用。bool它按索引比较每个元素并返回包含每个结果的 s 的新 valarray 。

事实上,valarrays的全部目的是实现对一组有序值的快速简单的操作,而不必在任何地方都写循环。

于 2014-07-08T10:01:11.530 回答