1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
// This is an independent project of an individual developer. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::sort;
using std::unique;
class Item
{
public:
Item(const string& name): mName(name), mAmountOwned(0)
{}
Item() = default;
string GetName() const { return mName; }
int GetAmountOwned() const { return mAmountOwned; }
void IncrementAmountOwned(int amount);
private:
string mName{ "Item Name" };
int mAmountOwned{ 0 };
};
void Item::IncrementAmountOwned(int amount)
{
mAmountOwned += amount;
}
class Inventory
{
public:
Inventory(): mInventory(0)
{}
void Add(Item& item, const string& itemName, int amount);
void Open();
private:
vector <std::pair<string, int>> mInventory;
Item item;
};
void Inventory::Add(Item& item, const string& itemName, int amount)
{
int wordAppearance{ -1 };
int index{ 0 };
for (int position = item.GetName().find(itemName, 0); position != string::npos; position = item.GetName().find(itemName, position))
{
cout << "Found " << ++wordAppearance << " instances of " << itemName << " at position " << position << endl;
position++;
}
if (wordAppearance == 0)
{
mInventory.push_back(std::make_pair(item.GetName(), amount));
}
else
{
cout << "Item already exists" << endl;
item.IncrementAmountOwned(amount);
}
}
void Inventory::Open()
{
for (auto& i : mInventory)
{
cout << i.first << " " << i.second << endl;
}
}
int main()
{
vector<string> inv;
inv.push_back("Potion");
inv.push_back("Map");
Item Potion("Potion");
Item Map("Map");
Inventory PlayerInventory;
PlayerInventory.Add(Potion, Potion.GetName(), 3);
PlayerInventory.Add(Map, Map.GetName(), 1);
PlayerInventory.Add(Potion, Potion.GetName(), 3);
PlayerInventory.Add(Potion, Potion.GetName(), 3);
PlayerInventory.Add(Potion, Potion.GetName(), 3);
PlayerInventory.Open();
}
|