Вы можете сделать std::vector
всех ваших областей и инициализировать их начальными значениями с помощью списка инициализаторов.Затем вы можете зациклить их, используя диапазон, основанный на цикле.
#include <vector>
class Area {
double m_coal;
double m_copper;
double m_iron;
double m_amber;
double m_gold;
bool m_active;
public:
Area(double coal, double copper, double iron, double amber, double gold) :
m_coal(coal), m_copper(copper), m_iron(iron), m_amber(amber), m_gold(gold), m_active(false)
{}
bool is_active() const { return m_active; }
};
int main() {
// initialize all areas
std::vector<Area> areas = {
{1., 0., 0., 0., 0.},
{0.7, 0., 0., 0., 0.},
{.5950, 0.2833, 0.0917, 0.025, 0.005}
};
for (auto& area : areas) {
if (area.is_active()) {
// do stuff
}
}
}
Если вы хотите сделать еще один шаг вперед, вы можете упростить обработку ресурсов, поместив их в std::array
.Возможно, вы захотите расширить список ресурсов на один день, который будет очень трудоемким, если все они будут жестко закодированы везде.Более мягкий подход может выглядеть примерно так:
#include <iostream>
#include <initializer_list>
#include <array>
#include <vector>
// append to the list when you invent a new resource
enum Resource : size_t { coal, copper, iron, amber, gold, LAST=gold, COUNT=LAST+1 };
class Area {
std::array<double, Resource::COUNT> m_resources;
bool m_active;
public:
Area(std::initializer_list<double> il) :
m_resources(),
m_active(false)
{
std::copy(il.begin(), il.end(), m_resources.begin());
}
double get(Resource x) const { return m_resources[x]; }
void set(Resource x, double value) { m_resources[x]=value; }
void add(Resource x, double value) { m_resources[x]+=value; }
void set_active() { m_active=true; }
void set_inactive() { m_active=false; }
bool is_active() const { return m_active; }
};
int main() {
// initialize all areas
std::vector<Area> areas = {
{1.},
{0.7},
{.5950, 0.2833, 0.0917, 0.025, 0.005},
{.1232, 0.3400, 0.0000, 0.234, 0.001}
};
areas[0].set_active(); // just for testing
for (auto& area : areas) {
if (area.is_active()) {
// do stuff
std::cout << "coal before: " << area.get(coal) << "\n";
area.add(coal, -0.1);
std::cout << "coal after : " << area.get(coal) << "\n";
}
}
}