Reputation: 101
Is there any practical way to get objects to work with maps? (I don't really know much about maps so sorry if this is a bad question). I'm interested in using a map for an inventory system that will contain item objects. An item object has a name, description, and money value. The key would be the item's name, and the linking variable would be the the quantity of items I have for that particular item.
And if a map doesn't work, does anyone have a good alternative to this type of system? I need something keeping track of the quantity of each type of item I have.
Upvotes: 0
Views: 1785
Reputation: 5297
The C++ standard library template map
is just a storage container so it can definitely be used with objects. The map will take your object as its templated argument parameter.
A map would work well for your inventory system. Use something like:
#include <pair>
#include <map>
#include <string>
#include <iostream>
class Item {
public:
Item(void) {}
~Item(void) {}
Item(std::string new_name) {
my_name=new_name;
}
void setName(std::string new_name) {
my_name= new_name;
}
std::string getName(void) {
return my_name;
}
private:
std::string my_name;
};
class Item_Manager {
public:
Item_Manager(void) {}
~Item_Manager(void) {}
void addItem(Item * my_item, int num_items) {
my_item_counts.insert( std::pair<std::string,int>(Item.getName(),num_items) );
}
int getNumItems(std::string my_item_name) {
return my_item_counters[my_item_name];
}
private:
std::map<std::string, int> my_item_counts;
};
main () {
Item * test_item = new Item("chips");
Item * test_item2 = new Item("gum");
Item_Manager * my_manager = new Item_Manager();
my_manager->addItem(test_item, 5);
my_manager->addItem(test_item2,10);
std::cout << "I have " << my_manager->getNumItems(test_item->getName())
<< " " << test_item->getName() << " and "
<< my_manager->getNumItems(test_item2->getName())
<< " " << test_item2->getName() << std::endl;
delete test_item;
delete test_item2;
delete my_manager;
}
Here's a reference on the stdlib map and its functions: http://www.cplusplus.com/reference/stl/map/
Look at the function pages for examples of how to iterate through/index a map, etc.
Upvotes: 4
Reputation: 263220
I need something keeping track of the quantity of each type of item I have.
How about std::vector<std::pair<Item, int> >
?
Upvotes: 1
Reputation: 53319
If you're talking about std::map
, it's a template which can work with any type of object, as long as a way to compare objects for ordering is provided. Since your key (the name) is a string, it will work right out of the box with std::map
struct Item
{
std::string description;
int value;
};
int main()
{
// associate item names with an item/quantity pair
std::map<std::string, std::pair<Item, int> > itemmap;
}
Upvotes: 3