簡體   English   中英

如何在矢量中搜索結構項?

[英]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 == ,比較itemNamedamage

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM