Hi, how can I store an object in a hash_map? I have an Item object and I want to pair it with a quantity. Will I be able to: 1. Find the item? 2. change the paired quantity? 3. sort it by qty or item name?

/*Item.h handles the item in game*/

#ifndef ITEM_H
#define ITEM_H
#include <string>

class Item
{
public:
    Item(): name("NoName"), desc("NoDesc"), used(false){};
    Item(std::string IDesc, std::string IName) : name(IName), desc(IDesc), used(false){};
    ~Item(){};
    bool useable(){ return !used; }
    void useItem(){ used = true; }
    std::string getName() const { return name; }
    std::string getDesc() const { return desc; }
private:
    std::string name;
    std::string desc;
    bool used;
};
#endif

Recommended Answers

All 6 Replies

If you want to store an object in a hash map then you need to create a hashing function that will convert the object into a hash value.

How is that done? do I make it inside the item class and have it return a value?

You could do it that way. You could also have a function that takes an item object and returns a hash value. If you want to use standard containers then you would need to make it an external function and give that function to the container upon creation.

why not just use a map? so that way you do not have to worry about figuring out the logic for a hashing function that will not return the same key value for different values that you are inserting into the hash table

Item itemA("itemA", "des", true);
std::map <string, int> item_list;

// when you collect an item, check the map
item_list<string, int>::iterator it = item_list.find(itemA.getName());
if(it != m.end())  // item is already in the map
{

   item_list[itemA.getName()]++;
}
else // add it to the map
{
    item_list.insert ( std::pair<string,int>(itemA.getName(),1) );
}

uonsin you are only storing the name of the item. How would you retrieve the description with the method you have?

There are many ways you could do that. You could have a list of all items in the game and search for the one that matches the map key in order to use it, you could have an other map witht the key based on the item name and store an item object, you could have the item class keep track of how many objects of that class the player has and have the map hold a single item object instead of the count of how many items of that type the player has.

It is up to you on figureing out which is the best approach for what you are trying to do

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.