C++逻辑为真的一元函数
C++ unary function for logical true
>我正在尝试在布尔向量上使用any_of函数。 any_of函数需要一个返回布尔值的一元谓词函数。 但是,当输入到函数中的值已经是我想要的布尔值时,我不知道该使用什么。 我会猜测一些函数名称,如"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; }
);
这是一个活生生的例子。
当然,您也可以使用函子:
struct logical_true {
bool operator()(bool x) { return x; }
};
// ...
bool anyValid = std::any_of(testVec.begin(), testVec.end(), logical_true());
这是该版本的一个实时示例。
看起来你想要一个类似标识函数的东西(一个返回它传递的任何值的函数)。 这个问题似乎表明std::
中不存在这样的事情:
只返回传递值的默认函数?
在这种情况下,最简单的事情可能是编写
bool id_bool(bool b) { return b; }
然后就用它。
我最终在这里寻找一个C++标准库符号来做到这一点:
template<typename T>
struct true_ {
bool operator()(const T&) const { return true; }
};
我认为这是操作想要的,可以使用,例如,如下所示:
std::any_of(c.begin(), c.end(), std::true_);
我在标准库中找不到这样的东西,但上面的结构有效并且足够简单。
虽然上面的any_of
表达式单独没有意义(除非c
为空,否则它总是返回true
),但true_
的有效用例是作为需要谓词的模板类的默认模板参数。
截至 C++20,我们得到 std::identity
,这可能会有所帮助。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- 如何在 std::transform 中使用 std::p ow 作为一元函数?
- 位集构造函数中的一元按位或折叠
- 替换包含已弃用的一元函数的自定义模板
- 为什么指向非静态成员函数的指针不能用作标准库算法的一元谓词
- 具有成员函数的一元谓词
- 在函数调用之前,一元运算符会否定运算符
- C++逻辑为真的一元函数
- 如何从函数模板类成员内的转换算法参数指向一元运算符函数
- 运算符重载:一元运算符重载函数返回在此代码中如何工作
- 将一元函数应用于向量的某些元素的良好实现是什么?
- 使用 +(一元加号)解决 lambda 的函数指针和 std::function 上的不明确重载
- 一元函数,接受迭代器元组并产生基本类型
- 用于普通操作的STD一元函数