在数据检索中使用矢量值

Using vector values in data retrieval

本文关键字:数据 检索      更新时间:2023-10-16

我正在尝试在向量调用中使用向量。这项工作:

void calc_equipment(auto &gamedata, auto &player)
{
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].weapon.STR;
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].armor.STR;
}

但事实并非如此:

void calc_equipment(auto &gamedata, auto &player)
{
vector<string> types;
types.resize(2);
types[0] = "weapon";
types[1] = "armor";

player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].types[0].STR;
player.equipment.STR += gamedata.items[gamedata.equipment[player.total.id].types[1].STR;
}

很明显,它不是这样工作的,但有人能给我指明正确的方向吗?如何构造和使用类型[]来检索正确的数据?我可以用整数代替字符串,但它也不起作用。最终目标是迭代这些计算,而不是手动写出它们。

干杯!

您的示例比以前复杂得多,但您似乎希望通过包含变量名称的字符串来操作变量。我不记得这种方法的名字了,但C++不支持它。

我认为最好的方法(如果你真的想这样做的话(是一个包装器,通过索引运算符使结构的成员可用。

class EquipmentWrapper
{
public:
EquipmentWrapper(Equipment &nE): E(nE)
{}
int operator[](unsigned int k) const
{
switch(k)
{
case 0: return E.weapon;
case 1: return E.armor;
default: throw(0);
}
}
private:
Equipment &E;
};
...
EquipmentWrapper W(gamedata.equipment[player.total.id]);
player.equipment.STR += W[0].STR;
player.equipment.STR += W[1].STR;

听起来您想要以反射的方式迭代结构的字段。没有如Beta所述的内置支持。

您可以为您的项目类型和称为设备的通用项目集合重载流式操作符。每个结构都知道如何将自己字符串化。您的客户端代码只是要求顶级设备将自己插入流中。以下示例:

using namespace std;
struct Weapon
{
Weapon(string const & nm) : name(nm) {}
string name;  
};
ostream& operator<<(ostream & os, Weapon const & w)
{
os << w.name;
return os;
}
struct Armor
{
Armor(string const & nm) : name(nm) {}
string name;
};
ostream& operator<<(ostream & os, Armor const & a)
{
os << a.name;
return os;
}
struct Equipment
{
Equipment(Weapon const & _w, Armor const & _a) : w(_w), a(_a) {}
Weapon w;
Armor a;
};
ostream& operator<<(ostream & os, Equipment const & e)
{
os << e.w << ", " << e.a;
return os;
}
int main()
{
Weapon w("sword of smiting");
Armor a("plate of deflection");
Equipment e(w, a);
//can be sstream just as well to collect into a string
cout << e << endl;
}