【问题标题】:Strange C++ compile error with valarrays带有 valarrays 的奇怪 C++ 编译错误
【发布时间】:2014-08-29 00:24:50
【问题描述】:

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

预期行为:输出true1 的一些变体

编译错误(使用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;
              ^

这个编译错误是什么意思,如何解决?

【问题讨论】:

    标签: c++ compiler-errors syntax-error std valarray


    【解决方案1】:

    问题在于将 valarrays 与 == 进行比较不会返回 bool,而是返回 std::valarray&lt;bool&gt;,按元素进行比较。

    如果你想比较它们是否相等,你可以在结果上调用min(),因为false &lt; true

    return (a*x==b).min();
    

    【讨论】:

    • 谢谢!我最初认为== 运算符在valarrays 和vectors 上的工作方式相同(即返回bool)。此外,我很惊讶比较 bools 不会导致编译错误。可惜没有更简单的方法来比较 valarrays 是否相等。
    • 这是低效的,因为它不会短路。有解决办法吗?
    【解决方案2】:

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

    确实,valarrays is to enable quick and easy operations on an ordered set of values 的全部目的,而不必到处写循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多