Greetings, I'm tryining to build a map that store a list of persons. I've previously worked with lists with no problem but since I'm using map I've this terrible problem...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Person; // This has an Id and a code both int
class Directory
{
public
map<int,Person> people;
map<int,Person>:: iterator it;
};
void Directory::loadPerson(map <int,Person> :: iterator & it)
{
int m = it->second->id;
this->people.insert(pair<int,Person> (m,it->second));
}
Error: Base operand '->' has non-pointer type 'it' at line of
int m = it->second->id;
If some can explin me please how i should use the iterators of maps passed by reference I will apreciate.
1) Answer to your question: *it returns pair<Key,Value>, so it would be it->second.id;
2) It is a bad practice to keep iterators as data members of a class. In general, iterators
should not live beyond the function scope in which they are used, simply because inserts
and/or deletes from a container may or may not invalidate any or all iterators held,
depending upon the location of the insert, location of the item to be removed, and
the container.
3) std::make_pair() is a useful utility function you can use in place of
pair<int,Person>(). In your case, you would use it as follows: std::make_pair( m, it->second ).
Typically you have to design around it. The "best" solution is heavily dependent upon
exactly what you are trying to accomplish. If you want more specific advice, then you'll
need to give me more details on the methods and what you are trying to do.
The two members of a pair, for a map are: pair<const Key, Value>
I see that you are trying to insert id as the second member (Value) of the pair. Typically ids are assigned to the KEY of a map, which is the first member.