如何否定lambda功能结果
How to negate a lambda function result
在以下内容中,有一个不编译的C 编写的代码段。原因是试图使用not1()扭转lambda函数的结果。如果有人可以修复此代码
,我将非常感谢#include <iostream> // std::cout
using namespace std;
#include <functional> // std::not1
#include <algorithm> // std::count_if
#include <vector>
int main () {
vector<int> sv = {3, 5, 10,12 };
vector<int> v = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
auto validSelection = [&](auto& e) {
auto isSelected = [&] (auto& sve) {
return e == sve;
};
return find_if(sv.begin(), sv.end(), isSelected) != sv.end();
};
stable_partition(v.begin(), next(v.begin(),8) , not1(validSelection));
for (int n : v) {
std::cout << n << ' ';
}
std::cout << 'n';
return 0;
}
一种方法是使用包装器std::function
。例如
auto even = [](int x) { return x % 2 == 0; };
std::cout << std::not1(std::function<bool(int)>(even))(11) << std::endl;
函数对象适配器not1
要求用作参数的相应谓词具有Typedef名称argument_type
和result_type
,并且包装器std::function
提供了它们。
在您的情况下,等效的呼叫看起来像:
stable_partition(v.begin(), next(v.begin(), 8) , not1(function<bool(int&)>(validSelection)));
演示。
,或者如果我正确理解了您要做的事情,那么相应的代码可以如以下示范程序所示
所示#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
int main()
{
std::vector<int> sv = { 3, 5, 10, 12 };
std::vector<int> v = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
auto validSelection = [&](int x)
{
return std::binary_search(sv.begin(), sv.end(), x);
};
std::stable_partition(v.begin(), v.end(), validSelection);
for (int x : v) std::cout << x << ' ';
std::cout << std::endl;
std::stable_partition(v.begin(), v.end(), std::not1( std::function<bool( int )>( validSelection) ) );
for (int x : v) std::cout << x << ' ';
std::cout << std::endl;
return 0;
}
在这种情况下,输出为
3 5 10 12 1 2 4 6 7 8 9 11 13 14 15
1 2 4 6 7 8 9 11 13 14 15 3 5 10 12
请注意使用算法std::binary_search
,因为对向量sv
进行了排序。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- valgrind-hellgrind与泄漏检查的结果不同
- 多态性和功能结合
- 用C++20 fmt限制结果的总大小
- 如何从主.cpp中的cpp文件中获取功能结果?
- 左移<<如何在不同的功能中给出不同的结果?
- STL:将功能应用于Adchacent_difference的结果,而无需额外的容器
- 检查数字在C 中未返回正确结果的功能
- 功能模板与Variadic模板过载:Intel C 编译器版本18产生的结果不同于其他编译器.英特尔是错误的
- 如何否定lambda功能结果
- 多功能阵列最后一行相同的结果
- 功能相同的代码,不同的结果
- 为什么我的功能(在二进制树上)打印出意外的结果
- 如何否定MEM_FN创建的功能指针的结果
- C 比较功能结果
- 如何打印添加功能的结果.
- 谁能告诉我为什么这些功能没有在合理的频谱中给我一个结果
- 地图的查找功能得到错误的结果
- 绕过虚拟模板功能以实现期望的结果