The Standard library's associative containers such as std::map
, std::set
, std::multiset
, std::multimap
, std::bitset
require that the ordering of elements must follow Strict Weak Ordering
, which means your implementation of operator<
must follow strict weak ordering. So one implementation could be this:
friend bool operator<(const MyKey& mk1, const MyKey& mk2)
{
if (mk1.string1 != mk2.string1 )
return mk1.string1 < mk2.string1;
else if ( mk1.string2 != mk2.string2)
return mk1.string2 < mk2.string2;
else if (mk1.string3 != mk2.string3)
return mk1.string3 < mk2.string3;
else
return mk1.uint1 < mk2.uint1;
}
Or you can implement it as:
friend bool operator<(const MyKey& mk1, const MyKey& mk2)
{
auto const & t1 = std::tie(mk1.string1, mk1.string2, mk1.string3, mk1.uint1);
auto const & t2 = std::tie(mk2.string1, mk2.string2, mk2.string3, mk2.uint1);
return t1 < t2;
}
In this solution, std::tie
function creates two tuples t1
and t1
of the references of the arguments passed to it, and then compare t1
and t2
using overloaded operator<
for std::tuple
instead. The operator< for tuple compares the elements lexicographically — strict-weak ordering is achieved..