逻辑真的 C++ 一元函数

use*_*600 6 c++ stl boolean predicate unary-operator

我正在尝试在 bool 向量上使用 any_of 函数。any_of 函数需要一个返回布尔值的一元谓词函数。但是,当输入到函数中的值已经是我想要的 bool 时,我无法弄清楚要使用什么。我会猜测一些函数名称,如“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;
}
Run Code Online (Sandbox Code Playgroud)

Sho*_*hoe 5

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

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

这里的一个活生生的例子。

当然,您也可以使用函子:

struct logical_true {
    bool operator()(bool x) { return x; }
};

// ...

bool anyValid = std::any_of(testVec.begin(), testVec.end(), logical_true());
Run Code Online (Sandbox Code Playgroud)

这里的该版本的一个活生生的例子。


And*_*nko 4

看起来您想要类似恒等函数(返回所传递的任何值的函数)之类的东西。这个问题似乎表明不存在这样的事情std::

仅返回传递值的默认函数?

在这种情况下,最简单的事情可能是写

bool id_bool(bool b) { return b; }
Run Code Online (Sandbox Code Playgroud)

就用它吧。