mikevil14rin
mikevil14rin

Reputation: 145

overloading operators for struct as map key

Hi I'm having problems overloading the operator of my struct for use as a key. Here is my struct which I intend to use as a map key, basically it has 2 char arrays:

struct FConfig
{
    char product[3];
    char exchange[4];
    bool operator < (const FConfig &rhs) const
    {
        return (strcmp(product, rhs.product) < 0 || 
                 strcmp(exchange, rhs.exchange <0));
    }
};

My comparison is as long as one of product or exchange does not equal to the rhs's, then the key is considered unique. I use this and I get "invalid operator <" during runtime. I'm totally new at creating keys, so I'm still having some trouble understanding the logic when overwriting the < operator. Appreciate any help, thanks!

Upvotes: 2

Views: 1040

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

Your confusion about how operator < should work is pretty common. You want it to look like this:

bool operator < (const FConfig &rhs) const
{
   int product_comparision = strcmp(product,rhs.product);
   if (product_comparision<0) return true;
   if (product_comparision>0) return false;
   return strcmp(exchange,rhs.exchange)<0;
}

Since product is your primary key, the only time you even consider the secondary key is if the primary key values are equal.

Upvotes: 4

Related Questions