C ++ unary function for boolean true

I am trying to use the any_of function for bool's vector. The any_of function requires a unary predicate function that returns a bool. However, I cannot figure out what to use when the value entered into the function is already the bool that I want. I would suggest some kind of function name, such as "logical_true" or "istrue" or "if", but none of them work. I pasted the code below to show what I'm 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
source share
2 answers

You can use lambda (starting with 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());

.

+4

, - (, , ). , , , std:: :

, ?

bool id_bool(bool b) { return b; }

.

+2

All Articles