Connecting Tech Pros Worldwide Help | Site Map

newbie question:why does this code work...

Newbie
 
Join Date: Oct 2006
Posts: 4
#1: Apr 22 '07
hi all...
i found this code in some past discussion on this forum.i do not understand why operator overloading is necessary.if i remove it iam getting errors...
Expand|Select|Wrap|Line Numbers
  1. #include <map>
  2.  
  3. class Keys {
  4. public:
  5. Keys(int k1, int k2)  
  6. {
  7.       key1=k1;
  8.       key2=k2;
  9.  }
  10. bool operator<(const Keys &right) const {
  11. return (key1 < right.key1 && key2 < right.key2);
  12. }
  13. int key1;
  14. int key2;
  15. };
  16.  
  17. int main() {
  18. std::map<Keys, int> mymap;
  19. mymap.insert(std:air<Keys, int>(Keys(3, 8), 5));
  20. return 0;
  21. }
Moderator
 
Join Date: Mar 2007
Location: North Bend Washington USA
Posts: 5,366
#2: Apr 22 '07

re: newbie question:why does this code work...


You are using a map of Keys objects. A map is a tree of ordered values. The map insert needs to know how to compare objects by calling the < operator to preserve the order.
Newbie
 
Join Date: Oct 2006
Posts: 4
#3: Apr 22 '07

re: newbie question:why does this code work...


i get the gist of what you say.....
but plzzzzz can u explain more about the ordering a lil bit.....
it would be very helpful....
Newbie
 
Join Date: Oct 2006
Posts: 4
#4: Apr 22 '07

re: newbie question:why does this code work...


thank you for the previous explanation...
Reply