如何在向量中查找特定字符串并在if语句中使用它[duplicate]

时间:2023-02-05 23:50:20

This question already has an answer here:

这个问题在这里已有答案:

This is what my vector starts as:

这是我的矢量开始的:

vector<string> inventory;
inventory.push_back("sword");
inventory.push_back("armor");

the player of this game will be able to choose two of three items with this code block:

此游戏的玩家将能够使用此代码块选择三个项目中的两个:

while(paid < 2)
{
    cout << "choice: ";
    cin >> equip;
    ++paid;
    inventory.insert(inventory.begin(), equip);
}

if(paid == 2)
{
    cout << "\nYou are out of money\n";
}

then there is a character that will interact with one of the inventory items if you purchased it.

然后有一个角色,如果你购买它,它将与其中一个库存物品互动。

if((bazaar == "woman") || (bazaar == "WOMAN"))
{
    cout << "you approach the woman, and she gives you a look.";

    if(...)
    {

    }
}

in that second if statement, I want to be able to check for a string in the inventory vector, and have two separate things happen, depending on whether or not that string is in the vector somewhere.

在第二个if语句中,我希望能够检查清单向量中的字符串,并且发生两个单独的事情,具体取决于该字符串是否在某处的向量中。

(as a side note, this is code for a text based game played in the console window)

(作为旁注,这是在控制台窗口中播放的基于文本的游戏的代码)

1 个解决方案

#1


if(std::find(inventory.begin(), inventory.end(), std::string("sword")) != inventory.end())
    ...

do not forget to include <algorithm>

不要忘记包含

#1


if(std::find(inventory.begin(), inventory.end(), std::string("sword")) != inventory.end())
    ...

do not forget to include <algorithm>

不要忘记包含