STL - Map question

Started by
2 comments, last by JoeyBlow2 18 years, 1 month ago
Can you have a map such as this?


std::map<sockaddr_in, long>


sockaddr_in is defined in the winsock2.h. I want to be able to take an incoming ipaddress/port and convert it into an index. However, I get errors doing that.


1>f:\vs8\vc\include\functional(143) : error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' :
could not deduce template argument for 'const std::_Tree<_Traits> &' from 'const sockaddr_in'


Any ideas on how to fix this?
Advertisement
Give it a compare function/functor.

E.g.
struct CompareIP{   bool operator()( const sockaddr_in &one, const sockaddr_in &two ) const   {      if( one.host < two.host )      {         return true;      }      return one.port < two.port;   }};std::map<sockaddr_in, long, CompareIP>


[Edited by - Fruny on March 6, 2006 12:54:45 AM]
Usually you overload the '<' operator for your class. The reason is because a std::map is sorted into a tree internally, and if there is no way of comparing one object to another the map will not know how to sort them.

If you want a cheap way of doing it, it is possible to map a class pointer to something though, since it is very easy to compare pointer addresses (they are just numbers afterall). So you could have this:

std::map<Foo*, Bar>
Thanks for the help. :)

This topic is closed to new replies.

Advertisement