C++ 逻辑真一元函数

标签 c++ stl boolean predicate unary-operator

我正在尝试对 boolean vector 使用 any_of 函数。 any_of 函数需要一个返回 boolean 值的一元谓词函数。但是,当输入到函数中的值已经是我想要的 boolean 值时,我不知道该使用什么。我会猜测一些函数名称,如“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;
}

最佳答案

您可以使用 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是该版本的实例。

关于C++ 逻辑真一元函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20764642/

相关文章:

c++ - STL多重继承的remove()处理

c++ - 如何将 vector (或不同的容器)与不可复制的类一起使用?

c++ - boolean 值的大小是多少? 1 位还是 1 字节?

matlab 返回向量中每第二次出现的值

c++ - 如何从 'this'创建智能指针?

c++ - 为什么 Clang 会添加额外的 FMA 指令?

c++ - make_heap 的意义何在?

java - 了解 Java 中的 If 语句

c++ - 如何将 bool vector memcpy 到 char 数组?

c++ - 应急代码