views:

83

answers:

2
+2  Q: 

iterator for map

hello i am trying to make a map containing objects as the following : class Employee >>dervied from Employee : are the following classes : Worker , Manager and ViceManage. in my map i want to have the object Employee sorted by his ID which is char* i tried to create a map like this:`

multimap<const string,Employee*> t1
t1<string,Employee>::iterator myIterator;
Date e(17,6,1985);
Address a("somecity","somestreet",15,12);
ViceManager* d = new ViceManager("John","Doh","035845778", e,a,"03-9458353",10000,85,"gsdasda");
t1.insert(make_pair(d->GetId(),d));
myIterator=t1.begin();
myIterator->comp_value->PrintEmployee();

i got alot of problems in my code i would very much like to hear what you guys want to say thx in advance

+2  A: 

First of all, iterator is a type which is typedef'ed in multimap template class in your case. So you need to write the following:

multimap<const string,Employee*>::iterator myIterator;

As for second part of your question, you could add a new field in the Employee class that will identify employee type (Worker , Manager and ViceManage). Then cast depending on that field:

if ( myIterator->type == VICE_MANAGER ) 
  static_cast<ViceManager*>(*myIterator->second)->PrintEmployee();

If your classes are polymorphic (which is a preferred solution) you could call PrintEmployee without additional cast:

myIterator->second->PrintEmployee();
Kirill V. Lyadvinsky
I prefer`typedef t1::iterator myIterator;`so that I don't repeat the map's types in two places. (Single-Point-of-Truth or Dont-Repeat-Yourself) [http://en.wikipedia.org/wiki/Single_Point_of_Truth]
ArunSaha
Why are you suggesting downcasting before calling `PrintEmployee`? If its behaviour is different for different employee types, then it should be virtual.
Mike Seymour
@Mike Seymour, yes I missed that `PrintEmployee` is a member of the `Employee` class.
Kirill V. Lyadvinsky
+3  A: 

Really, only two errors there, both related to iterators.

multimap<const string,Employee*> t1;
multimap<string,Employee*>::iterator myIterator; //Note the corrected iterator type
Date e(17,6,1985);
Address a("somecity","somestreet",15,12);
Employee* d = new ViceManager("John","Doh","035845778", e,a,"03-9458353",10000,85,"gsdasda");
t1.insert(make_pair(d->GetId(),d));
myIterator=t1.begin();
myIterator->second->PrintEmployee(); //Note the way of accessing the value

I notice that this code isn't really taking advantage of the map functionality, I assume that's for other sections of the code.

Editing to fix some mistakes I missed

jkerian