Reputation: 452
So maps need you to implement the operator <
if you want to use custom objects as keys.
struct example{
example( int id, String stuff);
int id;
String stuff;
bool operator<( const example& rhs ) const;
}
bool example::operator<( const example& rhs ) const
{
if( id< rhs.id ) return true;
if( rhs.id< id) return false;
if( stuff< rhs.stuff) return true;
if( rhs.stuff< stuff) return false;
return false;
}
From the examples I have seen (see discussion: Why std::map overloaded operator < does not use the Compare ) just return true
if the lhs < rhs
...
<
operator? Is it because maps are doing binary search in the background to find if the key matched?example example1 = example(1,"a");
example example2 = example(2,"b");
map<example, String> mymap;
mymap.insert({example1,"hello"});
mymap.insert({example2,"world"});
cout << mymap[example(1,"a")] << endl;
It never asks for an implementation of the operator=
so how does it know the new object I have created is the same as the first entry of the map. Would it print "hello"?
Upvotes: 0
Views: 349
Reputation: 625
It stores values in a balanced binary tree, red black tree as usual, so comparison operator is required for this tree
also keep in mind that if a < b == false
and b < a == false
it is considered that a
is equal to b
Upvotes: 1