【问题标题】:C++ unary function for logical true逻辑真的 C++ 一元函数
【发布时间】:2013-12-24 17:27:17
【问题描述】:

我正在尝试在布尔向量上使用 any_of 函数。 any_of 函数需要一个返回布尔值的一元谓词函数。但是,当输入到函数中的值已经是我想要的布尔值时,我不知道该使用什么。我猜想一些函数名称,如“logical_true”或“istrue”或“if”,但这些似乎都不起作用。我在下面粘贴了一些代码以显示我正在尝试做的事情。提前感谢您的任何想法。 --克里斯

// Example use of any_of function.

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

int main(int argc, char *argv[]) {
    vector<bool>testVec(2);

    testVec[0] = true;
    testVec[1] = false;

    bool anyValid;

    anyValid = std::find(testVec.begin(), testVec.end(), true) != testVec.end(); // Without C++0x
    // anyValid = !std::all_of(testVec.begin(), testVec.end(), std::logical_not<bool>()); // Workaround uses logical_not
    // anyValid = std::any_of(testVec.begin(), testVec.end(), std::logical_true<bool>()); // No such thing as logical_true

    cout << "anyValid = " << anyValid <<endl;

    return 0;
}

【问题讨论】:

    标签: c++ stl boolean predicate unary-operator


    【解决方案1】:

    您可以使用 lambda(C++11 起):

    bool anyValid = std::any_of(
        testVec.begin(), 
        testVec.end(), 
        [](bool x) { return x; }
    );
    

    here 就是一个活生生的例子。

    当然,您也可以使用仿函数:

    struct logical_true {
        bool operator()(bool x) { return x; }
    };
    
    // ...
    
    bool anyValid = std::any_of(testVec.begin(), testVec.end(), logical_true());
    

    here 是该版本的一个活生生的例子。

    【讨论】:

      【解决方案2】:

      看起来你想要一个身份函数(一个返回它传递的任何值的函数)。这个问题似乎表明std:: 中不存在这样的东西:

      Default function that just returns the passed value?

      在这种情况下,最简单的方法可能是编写

      bool id_bool(bool b) { return b; }
      

      然后使用它。

      【讨论】:

        【解决方案3】:

        从 C++20 开始,我们得到 std::identity,这可能会有所帮助。

        【讨论】:

          【解决方案4】:

          我最终在这里寻找一个 C++ 标准库符号来执行此操作:

          template<typename T>
          struct true_ {
              bool operator()(const T&) const { return true; }
          };
          

          我认为是op想要的,可以使用的,例如,如下:

          std::any_of(c.begin(), c.end(), std::true_);
          

          我在标准库中找不到类似的东西,但是上面的结构可以工作并且很简单。

          虽然上面的any_of 表达式单独使用没有意义(它总是返回true,除非c 为空),但true_ 的有效用例是作为模板类的默认模板参数期待一个谓词。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2014-02-25
            • 1970-01-01
            • 2010-12-19
            • 2012-12-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多