将 std::function 作为参数传递给for_each
passing std::function as a parameter to for_each
#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::函数 ':调用的参数过多
我认为您想要的是以下内容
#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() );
^^^^
你需要
括号来唤起对sample_function
的函数调用,而函数调用又会为你for_each
返回std::function
对象:
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());
^^
}
现场演示
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用指向成员的指针将成员函数作为参数传递
- 如何将参数传递给正在使用模板的类
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 如何将部分流作为参数传递
- 我正在开发服务器,ip作为参数传递不起作用
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将参数传递为"const"的奇怪效果
- 如何在 c++ 中将函数作为参数传递?
- 在 C++ 中将非指定类型作为参数传递的最佳方法?
- 使用引用与指针将数组作为参数传递
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数