[英]How Do I Search For Struct Items In A Vector?
我正在尝试使用矢量实现创建库存系统,但我似乎遇到了一些麻烦。 我正在使用我制作的结构来解决问题。 注意:这实际上不是游戏代码,这是一个单独的解决方案,我用来测试我对矢量和结构的知识!
struct aItem
{
string itemName;
int damage;
};
int main()
{
aItem healingPotion;
healingPotion.itemName = "Healing Potion";
healingPotion.damage= 6;
aItem fireballPotion;
fireballPotion.itemName = "Potion of Fiery Balls";
fireballPotion.damage = -2;
vector<aItem> inventory;
inventory.push_back(healingPotion);
inventory.push_back(healingPotion);
inventory.push_back(healingPotion);
inventory.push_back(fireballPotion);
if(find(inventory.begin(), inventory.end(), fireballPotion) != inventory.end())
{
cout << "Found";
}
system("PAUSE");
return 0;
}
前面的代码给出了以下错误:
1> c:\\ program files(x86)\\ microsoft visual studio 11.0 \\ _vc \\ include \\ xutility(3186):错误C2678:二进制'==':找不到带有'aItem'类型左手操作数的运算符(或者没有可接受的转换)
还有更多错误,如果您需要,请告诉我。 我敢打赌,这是一件小而愚蠢的事,但我已经被它吵了两个多小时。 提前致谢!
find
与向量中的项目相等的内容。 你说你想使用字符串进行搜索,但是你没有为此编写代码; 它试图比较整个结构。 而且你还没有编写代码来比较整个结构,所以它给你一个错误。
最简单的解决方案是使用显式循环而不是find
。
如果find_if
字符串find
内容,请使用find_if
变量并编写一个查看字符串的谓词函数。 或者如果你想通过整个结构find
东西,你可以在结构上定义一个operator ==
,比较itemName
和damage
。
或者您也可以考虑使用map
或unordered_map
数据结构而不是vector
。 映射容器设计用于使用密钥(例如字符串)进行快速查找。
find
方法不知道如何比较两个aItem
对象的相等性。 您需要在结构定义中定义==
运算符,如下所示:
bool operator==(aItem other)
{
if (itemName == other.itemName && damage == other.damage)
return true;
else
return false;
}
这将允许find
确定两个aItem
对象是否相等,这是算法工作所必需的。
尝试类似的东西:
#include <iostream>
#include <vector>
using namespace std;
struct item {
item(string const name,int const damage):name_(name),damage_(damage) {
}
string name_;
int damage_;
};
int main(int argc, char** argv) {
vector<item *> items;
item healingPostion("cure light",-10);
item fireballPostion("fireball",10);
items.push_back(&healingPostion);
items.push_back(&fireballPostion);
if(find(items.begin(), items.end(), &fireballPostion) != items.end()) {
cout << "Found";
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.