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

Vla*_*nus 3 c++ structure 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;
}
Run Code Online (Sandbox Code Playgroud)

前面的代码给出了以下错误:

1> c:\ program files(x86)\ microsoft visual studio 11.0\_vc\include\xutility(3186):错误C2678:二进制'==':找不到带有'aItem'类型左手操作数的运算符(或者没有可接受的转换)

还有更多错误,如果您需要,请告诉我.我敢打赌,这是一件小而愚蠢的事,但我已经被它吵了两个多小时.提前致谢!

ami*_*itp 5

find寻找与向量中的项相等的东西.你说你想使用字符串进行搜索,但是你没有为此编写代码; 它试图比较整个结构.而且你还没有编写代码来比较整个结构,所以它给你一个错误.

最简单的解决方案是使用显式循环而不是find.

如果你想find按字符串做事,使用find_if变量并编写一个查看字符串的谓词函数.或者如果你想find通过整个结构来完成事情,你可以operator ==在比较两者itemName和结构的结构上定义一个damage.

或者您也可以考虑使用mapunordered_map数据结构而不是vector.映射容器设计用于使用密钥(例如字符串)进行快速查找.