Skip to content

Instantly share code, notes, and snippets.

@adabo
Created February 10, 2019 20:19
Show Gist options
  • Save adabo/1b3a8974cb20bd005fb41b3f21837724 to your computer and use it in GitHub Desktop.
Save adabo/1b3a8974cb20bd005fb41b3f21837724 to your computer and use it in GitHub Desktop.
Why is the result true when false is expected?
#include <iostream>
#include <vector>
enum ItemType
{
TORCH,
KEY,
GEM,
PEBBLE,
GOLD
};
class Item
{
public:
bool operator==(Item const& other) const {
return type == other.type;
}
Item(ItemType) : type(type) {}
ItemType type;
};
class Backpack
{
public:
Backpack(ItemType type)
{
m_items.push_back(type);
};
bool hasItem(ItemType type)
{
for (const auto &it_type : m_items) {
if (it_type == type)
return true;
else
return false;
}
return false;
}
void addItem(ItemType type) { m_items.push_back(type); }
std::vector<Item> m_items;
};
int main()
{
Backpack backpack(TORCH);
backpack.addItem(GEM);
backpack.addItem(PEBBLE);
backpack.addItem(KEY);
if (backpack.hasItem(GOLD))
std::cout << "Found.\n";
else
std::cout << "Not found.\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment