c++ - 如何否定 lambda 函数结果

标签 c++ algorithm c++11 lambda

下面有一个用 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_typeresult_type 以及包装器 std::function 提供它们。

在您的情况下,等效调用如下所示:

stable_partition(v.begin(), next(v.begin(), 8) , not1(function<bool(int&)>(validSelection)));

Demo.

或者如果我已经正确理解了你正在尝试做的事情,那么相应的代码可以看起来像下面的演示程序所示

#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的使用,因为 vector sv是排序的。

关于c++ - 如何否定 lambda 函数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47908839/

相关文章:

c++ - 重新绑定(bind) std::function 的一个参数

c++ - 从 VS 2012 中的 lambda 返回值构造 std::function 时崩溃

c++ - sqlite select 语句抛出的异常

c++ - 模板类的 child 也必须是模板类吗?

objective-c - 重置密码算法

c - 如果 Arduino 的库有 32 位限制,我如何在 Arduino 上输出 64 位数字?

c++ - vector::push_back 从 const Type* 到 type* 的转换

c++ - std::smatch str() 未返回正确的字符串

image - 如何改进我的图像比较算法

c++ - 使用 lambda 语法的优先级队列令人困惑