ベクターベースの在庫システムを機能させるのに問題があります。インベントリ内のアイテムを一覧表示することはできますが、ユーザーが選択したアイテムにアクセスすることを許可できません。コードは次のとおりです。
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;
}
編集:私はこれを正しく表現していないと思います。表示されるメッセージに影響を与えるには、プレーヤーの選択が必要です。1番目のスニペットの出力例は次のとおりです。
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、ゼロから始まるベクトルを反映する)を検索に渡して、(この小さな例では)次のかどうかを判断することです。 Inventory[choice-1]のアイテムは癒しのポーションです。もしそうなら、「あなたは癒しのポーションを使いました!」と表示します。そうでない場合は、「燃えるような喜びのボール」を表示します。