Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ unary function for logical true

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;
}
like image 747
user3130600 Avatar asked Dec 24 '13 17:12

user3130600


People also ask

Is a unary operator True or false?

Explanation: Unary operator as the name suggests is used to process the only one operand. For example, in a "++3",'++' is a unary operator that is known as an increment operator and in a "--3", "--" is a unary operator which is known as increment operator.

Are logical operators unary?

Unary Logical Operator (logical negation) operator produces the value 0 if its operand is true (nonzero) and the value 1 if its operand is false (0).

Which logical operator is unary operator?

Unary operators act on only one operand in an expression. The unary operators are as follows: Indirection operator ( * ) Address-of operator ( & )

Is ++ unary operator in C?

Types of Unary Operator in C unary minus (-) unary plus (+) decrement (- -) increment (++)


2 Answers

You can use a lambda (since C++11):

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

And here's a live example.

You can, of course, use a functor as well:

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

// ...

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

And here's a live example for that version.

like image 79
Shoe Avatar answered Sep 29 '22 00:09

Shoe


Looks like you want something like an identity function (a function that returns whatever value it is passed). This question seems to suggest no such thing exists in std:::

Default function that just returns the passed value?

In this case the easiest thing might be to write

bool id_bool(bool b) { return b; }

and just use that.

like image 35
Andrey Mishchenko Avatar answered Sep 28 '22 23:09

Andrey Mishchenko