gpt4 book ai didi

c++ - 将 std::function 作为参数传递给 for_each

转载 作者:搜寻专家 更新时间:2023-10-31 01:37:22 25 4
gpt4 key购买 nike

#include <initializer_list>
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>

std::function<void(int)> sample_function()
{
return
[](int x) -> void
{
if (x > 5)
std::cout << x;
};
}

int main()
{
std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
std::for_each(numbers.begin(), numbers.end(), sample_function);
}

我试图将 sample_function() 传递给 for_each 但我遇到了这个错误

错误 C2197“std::function”:调用的参数过多

最佳答案

我想你想要的是下面的

#include <iostream>
#include <vector>
#include <functional>

std::function<void(int)> sample_function = [](int x)
{
if (x > 5) std::cout << x << ' ';
};


int main()
{
std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
std::for_each(numbers.begin(), numbers.end(), sample_function);
}

输出是

10 15 20 25 35 45 50

或者,如果您确实想定义一个返回std::function 类型对象的函数,那么您可以这样写

#include <iostream>
#include <vector>
#include <functional>

std::function<void(int)> sample_function()
{
return [](int x)
{
if (x > 5) std::cout << x << ' ';
};
}


int main()
{
std::vector<int> numbers{ 1, 2, 3, 4, 5, 10, 15, 20, 25, 35, 45, 50 };
std::for_each(numbers.begin(), numbers.end(), sample_function() );
}

输出将与上图相同。注意通话

    std::for_each(numbers.begin(), numbers.end(), sample_function() );
^^^^

关于c++ - 将 std::function 作为参数传递给 for_each,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34208013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com