stl map

i was wondering how would i return a new item coming from a stl map
at the moment i have this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Declare outside
map<int, Item>ItemDataBase;

Item Item::CreateItem(int ID,Character C)
{
        map<int, Item>::iterator iter = ItemDataBase.find(ID);
	if(iter != ItemDataBase.end())
	{
		return  iter->second;
	}
	else
	{
		cout<<"Item not found"<<endl;
		return;
	}
}


i tried this and it didnt work
return new iter->second;
im curious is if there is another way to create a new item that is stored in the map
Last edited on
Did you tried ItemDataBase.second;..? i ain't sure about that but may be that work..
Did you insert a std::pair into the map? That's where first & second come from.

http://www.cplusplus.com/reference/map/map/insert/


HTH
@TheIdeasMan
AFAIK std::map only stores std::pairs

@imgregduh
You are searching an empty local map.
1
2
3
4
Item Item::CreateItem(int ID,Character C)
{
        map<int, Item>ItemDataBase;
        // ... 


ItemDataBase is destroyed when the function returns.

What you intended was perhaps something like this:

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
struct item
{
    public:
        item( int id, character c ) : id(id), who(c) {}

        // ...

    static item& create( int id, character c ) // C++98
    {
        std::map< int, item >::iterator iter = item_db.find(id) ;

        if( iter == item_db.end() )
            iter = item_db.insert( std::make_pair( id, item(id,c) ) ).first ;

        return iter->second ;
    }

    private:
        int id ;
        character who ;

        static std::map< int, item > item_db ;
};

std::map< int, item > item::item_db ;
the database is delcare on the outside

i have inserted items into the database like this
ItemDatabase[i]= item();
im trying to apply a factory pattern with a map data structure so that when i call somone from the itemdatabase its a new item obj this why i can simply delete it when its used
Topic archived. No new replies allowed.