6

I'm trying to use the any_of function on a vector of bool's. The any_of function requires a unary predicate function that returns a bool. However, I can't figure out what to use when the value input into the function is already the bool that I want. I would guess some function name like "logical_true" or "istrue" or "if" but none of these seem to work. I pasted some code below to show what I am trying to do. Thanks in advance for any ideas. --Chris

// 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;
}
4

4 回答 4

5

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

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

这是一个活生生的例子

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

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

// ...

bool anyValid = std::any_of(testVec.begin(), testVec.end(), logical_true());

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

于 2013-12-24T17:40:17.507 回答
4

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

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

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

bool id_bool(bool b) { return b; }

并使用它。

于 2013-12-24T17:31:26.203 回答
0

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

于 2020-09-14T06:40:23.417 回答
-1

我最终在这里寻找一个 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_is 作为一个需要谓词的模板类的默认模板参数。

于 2020-04-03T09:38:20.993 回答