C++ 传递函数作为参数,使用lambda集成对象

C++ 传递函数作为参数,使用lambda集成对象,c++,math,syntax,C++,Math,Syntax,出于教育目的 我有一个函数integrate,它接受std::function作为参数 double calculus::integralSimple(std::function<double(double)> fn, double begin, double end) { double integral = 0; for (long double i = begin; i < end; i += _step) { integral +

出于教育目的

我有一个函数integrate,它接受std::function作为参数

double calculus::integralSimple(std::function<double(double)> fn, double begin, double end)
{
    double integral = 0; 
    for (long double i = begin; i < end; i += _step)
    {
        integral += fn(i) * _step;  // _step defined in class 
    }
    return integral;
}
double演算::integralSimple(标准::函数fn,双开始,双结束)
{
二重积分=0;
用于(长双i=开始;i<结束;i+=\u步)
{
积分+=fn(i)*_步;/_步在类中定义
}
返回积分;
}
目前,我正在使用main.cpp调用此函数

calculus cl;
std::cout << cl.integralSimple(calculus::identity,0,1);
std::cout << cl.integralSimple([](double x) { return x*x; }, 0, 1);
微积分cl;
std::cout这正是设计的目的。语法如下所示:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

const double PI  =3.141592653589793238463;

double func(double v) { return std::sin(v); } // to avoid having to
                                              // cast std::sin

int main()
{
    using namespace boost::lambda;

    std::vector<double> v = {0, PI / 4, PI / 2, PI};

    std::for_each(v.begin(), v.end(),
        std::cout << _1 * bind(func, _1) - _1 * _1 << '\n'
    //                    ↑↑↑↑↑↑↑↑↑↑↑↑↑↑
    //                    to delay invocation of func
    );
}
#包括
#包括
#包括
#包括
#包括
#包括
常数双PI=3.141592653589793238463;
double func(double v){return std::sin(v);}//避免
//演员阵容
int main()
{
使用名称空间boost::lambda;
向量v={0,PI/4,PI/2,PI};
std::for_each(v.begin(),v.end(),

std::cout Boost的Lambda和Phoenix库可以做到这一点,但实际上,Lambda只包装表达式;它们不会干扰表达式。我没有将
intergalSimple
更改为
integralSimple
,但您可能应该这样做(如果我计算正确的话,可以更改五次)。我理解使用数学语言的愿望在编程方面。但我们确实需要接受编程语言和数学语言是不同的,比如英语、汉语和日语。我们确实需要接受以不太熟悉的形式表达相同的含义。@JonathanLeffler改变了它们。我的错。谢谢。我会尝试将其纳入我的代码中。如果你不介意我问的话,我会这样做吗S语法在任何其他语言中都是可能的。我计划在C++中实现函数,然后用Python调用它。所以在Python中我能做什么,直到允许用户简单地说“集成(x*x)”nnRaLes,我确信可以在Python中写入这样的库。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>

const double PI  =3.141592653589793238463;

double func(double v) { return std::sin(v); } // to avoid having to
                                              // cast std::sin

int main()
{
    using namespace boost::lambda;

    std::vector<double> v = {0, PI / 4, PI / 2, PI};

    std::for_each(v.begin(), v.end(),
        std::cout << _1 * bind(func, _1) - _1 * _1 << '\n'
    //                    ↑↑↑↑↑↑↑↑↑↑↑↑↑↑
    //                    to delay invocation of func
    );
}
auto x = _1;

auto sin(decltype(_1) ) {
    return bind(static_cast<double(*)(double)>(std::sin), _1);
}
std::for_each(v.begin(), v.end(),
    std::cout << x * sin(x) - x * x << '\n');