我正在尝试对 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/