Nadav
Nadav

Reputation: 2727

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

Upvotes: 2

Views: 725

Answers (2)

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99725

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();

Upvotes: 2

jkerian
jkerian

Reputation: 17066

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

Upvotes: 3

Related Questions