2

运行以下代码:

#include <iostream>
#include <boost/numeric/odeint.hpp>

using namespace std;
using namespace boost::numeric::odeint;

class CSystem
{
private:
    int counter=0;
public:

    void operator() ( const double &x , double &dxdt , const double t)
    {
        double mat_A=-1;
        double mat_B=1;

        dxdt=mat_A*x+mat_B*1;

        cout<<"counter: "<<counter<<endl;
        counter++; // seems it does not apply to the rest of the iterations appropriately
    }

    void solve()
    {
        double x;
        x = 0.0;
        typedef runge_kutta_dopri5<double> stepper_type;
        std::function<void(const double &,const double)> my_observer = [&](const double &x,const double t){/* do nothing*/};
        integrate_adaptive(make_controlled(1E-10,1E-10,stepper_type()),
                            *this,x,0.0,3.0,0.1,my_observer);
    }

};

int main()
{
    CSystem sys;
    sys.solve();
    return 0;
}

我希望counter从 0 开始计数并cout生成以下输出:

0
1
2
3
4
5
6
7
8
9
10
11
...

当我得到别的东西时:

counter: 0
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 0
counter: 1
counter: 2
counter: 3
...

什么是重置计数器?看起来很像!

解决这个问题的正确方法是什么?我宁愿避免使用外部对象。

4

1 回答 1

2

您的使用*this会复制您的 CSystem 对象,该对象可能会被进一步复制。

我认为您应该将该参数更改为std::ref(*this).

于 2015-01-17T22:03:19.460 回答