[英]sigma function with any function input
I have been making various functions that will compute the sigma in a range of very specific functions.我一直在制作各种函数,这些函数将在一系列非常具体的函数中计算 sigma。 I am now trying to write a sigma function that you would input a lambda or a function and it would then calculate the sum of its outputs within a range.
我现在正在尝试编写一个 sigma function ,您将输入一个 lambda 或 function 然后它会计算其输出的总和在一个范围内。 I have the iteration code done fine but now need to figure out how to input a lambda and call it inside that function.
我已经完成了迭代代码,但现在需要弄清楚如何输入 lambda 并在 function 中调用它。 here is my current code:
这是我当前的代码:
int sigma(int start, int end, ? function) {
if (start == end) {
return function(start);
}
else {
return function(start) + sigma(start + 1, end, function);
}
}
PS if anyone could help me make this not use recursion that would be amazing PS如果有人可以帮助我不要使用递归,那将是惊人的
You can make this function into a function-template:您可以将此 function 制作成函数模板:
template<typename Fn>
int sigma(int start, int end, Fn function) {
// ...
}
and then call it with a lambda:然后用 lambda 调用它:
auto lam = [](int) { return 42; };
std::cout << sigma(1, 5, lam);
To avoid the rescursion, the body could simply be:为了避免递归,身体可以简单地是:
int sum = 0;
for (int i = start; i <= end; ++i)
sum += function(i);
return sum;
You need the type for your parameter.您需要参数的类型。 So ask yourself what is this parameter supposed to be?
所以问问自己这个参数应该是什么? Based upon your definition of
sigma()
, you appear to be expecting a function-like object that is invoked with an int
parameter and returns an int
.根据您对
sigma()
的定义,您似乎期待一个类似 object 的函数,它使用int
参数调用并返回一个int
。 That is, a std::function<int(int)>
.也就是说,一个
std::function<int(int)>
。 Your function's declaration might end up looking like the following.您的函数声明最终可能如下所示。
int sigma(int start, int end, std::function<int(int)> & function);
If you want to handle functions with other signatures, then a function template might be more appropriate.如果您想处理具有其他签名的函数,那么 function 模板可能更合适。 See std::function vs template for a discussion.
请参阅std::function vs 模板进行讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.