【问题标题】:Illegal operand of type void when defining UnaryPredicate定义 UnaryPredicate 时 void 类型的非法操作数
【发布时间】:2020-05-07 15:11:57
【问题描述】:

我正在尝试将 std::partition 与自定义 UnaryPredicate 一起使用。

void Rank(vector< pair<double, string> >& pairs) const
{
    partition(pairs.begin(), pairs.end(), [](const pair<double, string>& a) { isnan(a.first); });
}

执行此操作时,我从 Visual Studio 2015 收到以下错误:

  • 错误 C2297 '&&':非法,右操作数有类型 'void' 成像 c:\program files (x86)\microsoft visual studio 14.0\vc\include\算法1839
  • 错误 C2171 '!':在类型为“void”的操作数上非法映像 c:\program files (x86)\microsoft visual studio 14.0\vc\include\算法1844
  • 错误 C2297 '&&': 非法,右操作数的类型为 'void' 映像 c:\program files (x86)\microsoft 视觉工作室 14.0\vc\include\算法 1844

以下没有问题:

bool pairIsNan(const pair<double, string>& a)
{
    return isnan(a.first);
}
partition(pairs.begin(), pairs.end(), pairIsNan);

谁能澄清第一组代码有什么问题以及如何解决?

【问题讨论】:

    标签: c++ std


    【解决方案1】:

    你的 lambda 没有返回任何东西,它对应的函数真的是这样的:

    void pairIsNan(const pair<double, string>& a)
    {
        // Discard the result of the isnan function
        (void) isnan(a.first);
    }
    

    要使其工作,您需要在 lambda 中返回 isnan 函数调用的结果:

    partition(pairs.begin(), pairs.end(), [](const pair<double, string>& a)
    {
        // Return the result
        return isnan(a.first);
    });
    

    【讨论】:

    • 这是一个愚蠢的错误。感谢您指出应该显而易见的事情。
    猜你喜欢
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2022-01-02
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多