如何在向量中搜索结构项?

How Do I Search For Struct Items In A Vector?

本文关键字:结构 搜索 向量      更新时间:2023-10-16

我正在尝试使用矢量实现创建一个库存系统,但我似乎遇到了一些麻烦。我在使用我制作的结构时遇到了问题。注意:这实际上不是在游戏代码中,这是我用来测试我对向量和结构的了解的单独解决方案!

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内容,请使用find_if变体并编写一个查看字符串的谓词函数。或者,如果您想通过整个结构find事物,您可以在结构上定义一个比较itemNamedamageoperator ==

或者,您也可以考虑使用mapunordered_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;
}