我试图使用向量实现来创建一个库存系统,但我似乎遇到了一些问题。我用我做的结构遇到了问题。注意:这实际上不是在游戏代码中,这是一个单独的解决方案,我是用来测试我的知识向量和结构!
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文件(x86)\microsoft visual studio 11.0\vc\include\x实用程序(3186):错误C2678:二进制'==‘:找不到使用'aItem’类型的左操作数的操作符(或者没有可接受的转换)
有更多的错误,如果你需要它,请告诉我。我敢打赌这是件又小又傻的事,但我已经对它猛敲了两个多小时了。提前感谢!
发布于 2012-11-09 18:55:15
find方法不知道如何比较两个aItem对象是否相等。您需要在结构定义中定义==操作符,如下所示:
bool operator==(aItem other)
{
if (itemName == other.itemName && damage == other.damage)
return true;
else
return false;
}这将允许find确定两个aItem对象是否相等,这是算法工作所必需的。
发布于 2012-11-09 18:48:45
find查找与向量中的项相等的内容。您说要使用字符串进行搜索,但还没有编写代码;它试图比较整个结构。您还没有编写代码来比较整个结构,所以这会给您带来一个错误。
最简单的解决方案是使用显式循环而不是find。
如果要按字符串对事物进行find,请使用find_if变量并编写一个查看字符串的谓词函数。或者,如果希望通过整个结构对事物进行find,则可以在结构上定义一个比较itemName和damage的operator ==。
或者您也可以考虑使用map或unordered_map数据结构而不是vector。映射容器是为使用键(例如字符串)快速查找而设计的。
发布于 2012-11-09 23:36:41
试一试如下:
#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;
}https://stackoverflow.com/questions/13317126
复制相似问题