微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有一种方法可以对此进行迭代,所以我不必添加每个函数?

如何解决有没有一种方法可以对此进行迭代,所以我不必添加每个函数?

是否有一种方法可以对此进行迭代,因此不必添加每个函数? 假设我有4个行星,我想将每个gforcex添加到planet [1] .forcex。 (来自n体仿真项目)

planet[1].forcex = 
    gforcex(planet[1].posx,planet[1].posy,planet[2].posx,planet[2].posy) 
  + gforcex(planet[1].posx,planet[3].posx,planet[3].posy) 
  + gforcex(planet[1].posx,planet[4].posx,planet[4].posy);

解决方法

这是一个简单的解决方案:

planet[1].forcex = 0;

for (int i : {2,3,4})
  planet[1].forcex += 
    gforcex(planet[1].posx,planet[1].posy,planet[i].posx,planet[i].posy);
,

这是std::accumulate的好去处。

#include <cmath>
#include <iostream>
#include <iterator>
#include <numeric>

using position_t = double;
using force_t = double;

class Planet {
public:
    Planet(position_t x,position_t y)
        : posx(x),posy(y),forcex(0)
    {}

    position_t posx;
    position_t posy;

    force_t forcex;
    
};

force_t gforcex(position_t a_x,position_t a_y,position_t b_x,position_t b_y) {
    return 1.0 / std::sqrt(std::pow(a_x - b_x,2) + std::pow(a_y - b_y,2));
}

int main() {
    Planet planet[] = {
        {1,2},{3,4},{-1,-2},{-3,-4}
    };

    for (auto& p : planet) {
        p.forcex = std::accumulate(
            std::begin(planet),std::end(planet),force_t(0),[&](const force_t& force,const Planet& other) {
                if (&p == &other) return force;
                else return force + gforcex(p.posx,p.posy,other.posx,other.posy);
            }
        );
    }

    for (int i = 0; i < sizeof(planet)/sizeof(planet[0]); ++i) {
        std::cout << "Planet " << i << " forcex: " << planet[i].forcex << "\n";
    }
}

这假定您的planet容器中装有Planet类型的对象。

对于#include <numeric>,您必须std::accumulate;对于#include <iterator>std::begin,您需要std::end,具体取决于{{1} }是。如果planet是标准容器planetstd::vector<Planet>,则std::array<Planet,N>planet.begin()也可以工作。

我建议致电planet.end() planet,因为那样更准确。

我建议将您的planets函数签名更改为gforcex

我建议对force_t gforcex(const Planet& a,const Planet& b);planet)使用标准库容器(可能是s,但也可以使用std::vector<Planet>)而不是数组当前正在使用数组。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。