【发布时间】:2012-11-01 05:25:57
【问题描述】:
我在让基于矢量的库存系统工作时遇到问题。我能够列出库存中的项目,但不能允许访问用户选择的项目。代码如下:
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;
}
编辑:我认为我没有正确表示这一点。我需要让玩家的选择影响显示的消息。这是第一个 sn-p 的示例输出:
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,以反映从零开始的向量)传递给 find,然后它将确定(在这个小例如)如果库存[选择 - 1] 中的物品是治疗药水。如果是这样,显示“你使用了治疗药水!”如果不是,则显示“快乐的火球”。
【问题讨论】:
-
不应该是
if (find(inventory.begin(), inventory.end() , healingPotion.itemName) != inventory.end())??此外,inventory.at(choice)将返回对该vector中特定对象值的引用,而不是对iterator的引用。 -
你看到了什么失败?
-
您的运营商应声明为:
bool operator==(const aItem& other) const -
1>----- 构建开始:项目:StructPractice,配置:调试 Win32 ------ 1> StructPractice.cpp 1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xutility(3186): error C2678: binary '==' : no operator found which take a left-hand operand of type 'aItem' (或者没有可接受的转换)
-
@VladimirMarenus:对,因为左边不是
const。看我的回答。
标签: c++ syntax if-statement vector find