[CSI] CS 3 - Map Internal Implementation

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Sep 26 08:42:47 EDT 2018


> 
> I have a quick question about how keys are ordered within maps. Say for
> example, we have a map that looks like this:
> 
> map<Student, int> myMap;
> 
> Where Student is the class that we have been defining over the past two
> weeks or so. Our class has two member variables; string firstName_ AND
> string lastName_. How is the key stored and ordered within the map in this
> case being that there are two strings for member variables within the
> Student class?
> 
> Since the key is a class that has member variables and member functions,
> then how are they keys being traversed? Is it by the first declared private
> member variable, or the second member variable OR is it even being stored
> by unique memory address's?
> 
> What if the key for a map is a different class that has a list and/or
> vector as private member variables, then what happens?
> 
> I hope my question makes sense so let me know what you think!

Excellent question!

For the objects to work as keys, the object has to have an overloaded
comparison operator implemented. The map internally invokes this
comparison to order map elements.

In the case of Student class, the students are ordered by last name
and then, if the two are equal, by first name. 

If you are curious, try to change this comparison to, for example, order
them by first name and see the difference in map order.

Thanks,
-- 
Mikhail


More information about the cs13001 mailing list