I have a problem with the operator<() method which is required for a std::map. I’m using a struct as composite key that looks as follows:
struct MyKey {
std::string string1;
std::string string2;
std::string string3;
unsigned int uint1;
friend bool operator<(const MyKey& mk1, const MyKey& mk2)
{
return mk1.string1 < mk2.string1 && mk1.string2 < mk2.string2 &&
mk1.string3 < mk2.string3 && mk1.uint1 < mk2.uint1;
}
}
As introduced I want to use a composite key with 4 values, but I don’t know how to achieve this for the operator< method. I observed that only 1 value is stored at a time!
Can anybody tell me how the right condition looks like?
Thanks in advance!
The Standard library’s associative containers such as
std::map,std::set,std::multiset,std::multimap,std::bitsetrequire that the ordering of elements must followStrict Weak Ordering, which means your implementation ofoperator<must follow strict weak ordering. So one implementation could be this:Or you can implement it as:
In this solution,
std::tiefunction creates two tuplest1andt1of the references of the arguments passed to it, and then comparet1andt2using overloadedoperator<forstd::tupleinstead. The operator< for tuple compares the elements lexicographically — strict-weak ordering is achieved..