使用STD ::查找从向量中选择项目

Using std::find To Choose An Item From A Vector

本文关键字:选择 向量 项目 STD 查找 使用      更新时间:2023-10-16

我有一个问题,使基于向量的库存系统工作。我能够列出库存中的项目,但不能允许访问用户选择的项目。这是代码:

struct aItem
{
    string  itemName;
    int     damage;
    bool operator==(aItem other)
    {
        if (itemName == other.itemName)
            return true;
        else
            return false;
    }
};
int main()
{
    int selection = 0;

    aItem healingPotion;
    healingPotion.itemName = "Healing Potion";
    healingPotion.damage= 6;
    aItem fireballPotion;
    fireballPotion.itemName = "Potion of Fiery Balls";
    fireballPotion.damage = -2;
    aItem testPotion;
    testPotion.itemName = "I R NOT HERE";
    testPotion.damage = 9001;
    int choice = 0;
    vector<aItem> inventory;
    inventory.push_back(healingPotion);
    inventory.push_back(healingPotion);
    inventory.push_back(healingPotion);
    inventory.push_back(fireballPotion);
    cout << "This is a test game to use inventory items. Woo!" << endl;
    cout << "You're an injured fighter in a fight- real original, I know." << endl;
    cout << "1) Use an Item. 2) ...USE AN ITEM." << endl;
switch (selection)
    {
    case 1:
        cout << "Which item would you like to use?" << endl;
        int a = 1;
        for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ ) 
        {
            cout << "Item " << a << ": " <<  inventory[index].itemName << endl;
            a+= 1;
        }
        cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
        cin >> choice;

^^^^在这一行之上的一切,都可以。我认为我的问题是if语句,但是我无法弄清楚我的语法中出错了哪里,或者有更好的方法可以做我正在做的事情。

        if (find(inventory.begin(), inventory.at(choice), healingPotion.itemName) != inventory.end())
            cout << "You used a healing potion!";
        else
            cout << "FIERY BALLS OF JOY!";
        break;
    case 2:
        cout << "Such a jerk, you are." << endl;
            break;
    }

编辑:我认为我没有正确地表示。我需要选择玩家的选择来影响显示的消息。这是第一个片段的样本输出:

Item 1: Healing Potion
Item 2: Healing Potion
Item 3: Healing Potion
Item 4: Potion of Fiery Balls
MAKE YOUR CHOICE. 
Choice: 

从那里开始,玩家可以键入1-4,我想要的是数字(负1,以从零开始)将其传递给发现,然后将其确定(在这个小的小示例)如果库存中的项目[选择-1]是一种治愈药水。如果是这样,请显示"您使用了治愈药水!"如果不是这样,要展示"欢乐的火球"。

三个问题。

一个,您的操作员应被声明为:

bool operator==(const aItem& other) const

两个,在此代码中:

find(inventory.begin(), inventory.at(choice), healingPotion) != inventory.end())

您没有搜索从begin()end()的整个向量 - 您仅搜索从begin()at(choice),其中at(choice)指向您搜索集的一past-the-end。因此,您要么要这样做:

find(&inventory.at(0), &inventory.at(choice), healingPotion) != &inventory.at(choice))

或这个...

find(inventory.begin(), inventory.end(), healingPotion.itemName) != inventory.end())

编辑三,您正在尝试将苹果与橙色进行比较。您正在搜索aItem对象的vector来查找匹配的aItem对象,但是您发送到find的参数不是aItem对象,它是aItem数据成员之一。

您应该搜索匹配的项目,例如:

find( inventory.begin(), inventory.end(), healingPotion ) != inventory.end() )
                                            ^^^^^^^^

在C 03中,您可以提供一个函子:

#include <functional>
struct match_name : public std::unary_function<aItem, bool>
{
    match_name(const string& test) : test_(test) {}
    bool operator()(const aItem& rhs) const
    {
        return rhs.itemName == test_;
    }
private:
  std::string test_;
};

...然后使用find_if搜索匹配:

find_if( inventory.begin(), inventory.end(), match_name(healingPotion.itemName) ) // ...

在C 11中,您可以使用闭合来简化此烂摊子:

string test = healingPotion.itemName;
if( find_if( inventory.begin(), inventory.end(), [&test](const aItem& rhs)
{
    return test == rhs.itemName;
}) == inventory.end() )
{
  // not found
}

要添加到约翰·迪布林(John Dibling)的答案中,最后一部分是您正在寻找名称,而不是AITEM。

所以要么需要:

find(inventory.begin(), inventory.end(), healingPotion) != inventory.end();

其中operator ==定义为:

bool operator==(const aItem& other) const
{
   return itemName == other.itemName;
}

否则您需要让操作员==取一个字符串:

find(inventory.begin(), inventory.end(), healingPotion.itemName) != inventory.end();

其中operator ==定义为:

bool operator==(const std::string& name) const
{
   return itemName == name;
}

而不是:

case 1:
        cout << "Which item would you like to use?" << endl;
        int a = 1;
        for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ ) 
        {
            cout << "Item " << a << ": " <<  inventory[index].itemName << endl;
            a+= 1;
        }
        cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
        cin >> choice;
        if (find(inventory.begin(), inventory.at(choice), healingPotion.itemName) != inventory.end())
            cout << "You used a healing potion!";
        else
            cout << "FIERY BALLS OF JOY!";
        break;
    case 2:
        cout << "Such a jerk, you are." << endl;
            break;
    }

我忽略了意识到向量的奇观之一是能够直接访问价值的能力 - 瑞安·古斯里(Ryan Guthrie)在他的评论中提到了这一点,但我发现了一个更简单的"答案"。即:

case 1:
    cout << "Which item would you like to use?" << endl;
    //TODO: Learn what the hell the following line actually means.
    for( vector<aItem>::size_type index = 0; index < inventory.size(); index++ ) 
    {
        //Makes a numerical list.
        cout << "Item " << index + 1 << ": " <<  inventory[index].itemName << endl;
        a+= 1;
    }
    cout << "MAKE YOUR CHOICE." << endl << "Choice: ";
    cin >> choice;
    //Cannot define this outside of the statement, or it'll initialize to -1
    invVecPos = (choice - 1);
    //This checks for an invalid response. TODO: Add in non-int checks. 
    if ((invVecPos) >= inventory.size())
    {
        cout << "Choice out of bounds. Stop being a dick." << endl;
    }
    //If the choice is valid, proceed.
    else
    {
        //checking for a certain item type.
        if(inventory[invVecPos].itemType == "ITEM_HEALTHPOT")
        {
            cout << "You used a healing potion!" << endl;
            //this erases the potion, and automagically moves everything up a tick.
            inventory.erase (inventory.begin() + (invVecPos));
        }
        else if(inventory[invVecPos].itemType == "ITEM_FIREPOT")
        {
            cout << "FIERY BALLS OF JOY!" << endl;
        }
        else
        {
            //error-handling! Whee!
            cout << "Invalid Item type" << endl;
        }
    }

    break;
case 2:
    cout << "Why do you have to be so difficult? Pick 1!" << endl;
    break;

谢谢Ryan-随着您的兴趣,我可以在其他地方查看并找到所需的代码!对"固定"代码进行了大量评论,因此遇到问题的其他任何人都应该能够收集他们的需求!