是否有一种方法可以对此进行迭代,因此不必添加每个函数? 假设我有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[1].posy, planet[3].posx, planet[3].posy)
+ gforcex(planet[1].posx, planet[1].posy, planet[4].posx, planet[4].posy);
答案 0 :(得分:2)
这是一个简单的解决方案:
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);
答案 1 :(得分:1)
这是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
是标准容器planet
或std::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>
)而不是数组当前正在使用数组。