在数据检索中使用矢量值
Using vector values in data retrieval
我正在尝试在向量调用中使用向量。这项工作:
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;
}
相关文章:
- 如何在Qt中从数据库中检索二进制数据?
- 两个垫子的 OpenCV 数据是相同的,但使用 Mat::at 检索时的值已损坏
- 打印从SQLite3数据库检索的数据C++与命令行中相同的方式
- 通过 host() 从 af::array 检索数据会导致错误的数据
- Winsock 数据不是从 IP 检索的,而是从普通 URL 检索的
- 在数据检索中使用矢量值
- 无法从 SQL Server 检索数据
- sd_journal_send发送二进制数据.如何使用日志检索数据?
- 无法在可视C++中检索资源文件数据
- 在 c++ 中使用指向对象的指针检索数据
- Getter 函数,用于在 2d 数组是类的数据成员时检索 2d 数组元素
- 从新实例的向量中检索数据返回 0
- 如何通过串行终端检索数据而不破坏其在 GNU ARM 嵌入式中的基本值?
- QNETWORK停止连接并检索数据
- 将 JSON 对象作为参数在 JNI 中传递给 CPP,并在 CPP 中检索 JSON 对象的数据
- 相机校准数据检索
- boost asio async_receive_from()在连续发送帧时缺少udp帧数据检索
- 数据检索和索引
- 结构"node"的迭代器不允许数据检索
- Matlab引擎数据检索失败