problem with map,iterator
Apr 28, 2011 at 3:14pm UTC
i need some class database (factory) for my program
i created it using std::map
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
template <class Obj>
class Factory
{
public :
Factory(){}
~Factory(){}
void Add(int ID);
Obj Ret(int ID);
private :
typedef std::map<int , Obj> mapa;
mapa z;
};
template <class Obj>
void Factory<Obj>::Add(int ID)
{
Obj t;
z.insert(mapa::value_type(ID, t));
}
template <class Obj>
Obj Factory<Obj>::Ret(int ID)
{
mapa::const_iterator i = z.find(ID);
return i->second;
}
some class
1 2 3 4 5 6 7 8 9 10
class car
{
private :
int a;
public :
car():a(0){}
~car(){}
void Init(int aa){a=aa;}
void Honk(){cout<<a<<"honk!\n" ;}
};
now i create database of cars and add 2 cars and init them
1 2 3 4 5
Factory<car> fCar;
fCar.Add(1);
fCar.Add(2);
fCar.Ret(1).Init(25);
fCar.Ret(2).Init(78);
now "a" in first car suposed to have number 25, but it has 0.
second car has 0 too.
when i run debugging, in function Init, the "a" has diferent addres as "a" in car. so it copy number from "aa" to wrong addres. but how it is posible? am i using iterator in wrong way?
Apr 28, 2011 at 4:03pm UTC
Make your Ret function return a reference and see if it works.
Also, you need a non const iterator.
1 2 3 4 5 6
template <class Obj>
Obj & Factory<Obj>::Ret(int ID)
{
mapa::iterator i = z.find(ID);
return i->second;
}
Last edited on Apr 28, 2011 at 4:05pm UTC
Apr 28, 2011 at 6:38pm UTC
You'll need to post a small complete program that exhibits the problem in order for people to help you.
Apr 30, 2011 at 8:23am UTC
thanks m4ster r0shi it helped a lot
Topic archived. No new replies allowed.