如何在向量中搜索结构项?
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
内容,请使用find_if
变体并编写一个查看字符串的谓词函数。或者,如果您想通过整个结构find
事物,您可以在结构上定义一个比较itemName
和damage
的operator ==
。
或者,您也可以考虑使用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;
}
相关文章:
- C++ 中具有 O(1) 搜索时间复杂度的数据结构
- 在树结构.txt文件中搜索节点
- 搜索并替换结构向量中的值
- 如何二进制搜索结构向量并在适当的索引处插入
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- 用户输入字符串的结构的搜索向量
- 在 c++ 上搜索结构中的对象
- C++ 使用数组结构创建平衡的二叉搜索树
- 如何在结构的“std::list”中搜索
- 在地图中搜索结构元素
- 在树结构中搜索数据
- 用于高效搜索的数据结构
- C++二叉搜索树实现,动态数组或结构/类
- 多种搜索组合的数据结构设计
- 从C++二进制搜索树中删除一个节点(类而非结构)
- 哪种数据结构是在一个向量中搜索和计数对象对的最佳数据结构
- 获取成功的二进制搜索树C 数据结构
- 如何在结构中的数组中搜索
- C++:用于快速搜索的数据结构
- 如何在向量中搜索结构项?