Dbo: Composite foreign key primary keys operator<, operator==
Added by Rob Farmelo over 13 years ago
Hi,
In tutorial8.C some operators are defined for < and . I\'m not sure how these are used, but wanted to make sure that what I\'m doing makes sense. My implementation of the operator is probably OK, but I'd like to implement the < operator as shown below because I'm using an automated process to do it and it's a littler easier if I can do it that way.
For a composite key with say 3 foreign key elements, are these reasonable ways to implement the operators?
struct TableD_id {
dbo::ptr<TableA> tableA;
dbo::ptr<TableB> tableB;
dbo::ptr<TableC> tableC;
TableD_id () { }
TableD_id (
dbo::ptr<TableA> a,
dbo::ptr<TableB> b,
dbo::ptr<TableC> c):
tableA (a),
tableB (b),
tableC (c)
{}
// Operators needed for new struct
bool operator== (const TableD_id& other) const
{
bool retval =
tableA == other.tableA &&
tableB == other.tableB &&
tableC == other.tableC ;
return retval;
}
bool operator< (const TableD_id& other) const
{
bool retval;
retval =
tableA < other.tableA ||
tableB < other.tableB ||
tableC < other.tableC;
return retval;
}
};
Queries built on this implementation seem to be working just fine.
Where are these operations used anyway? Tree traversals?
Thanks,
Rob
Replies (3)
RE: Dbo: Composite foreign key primary keys operator<, operator== - Added by Rob Farmelo over 13 years ago
For some reason the "==" symbol was removed from my post text. Here's a restatement of that text:
Hi,
In tutorial8.C some operators are defined for < and ==. I'm not sure how these are
used, but wanted to make sure that what I'm doing makes sense. My implementation
of the == operator is probably OK, but I'd like to implement the < operator as
shown below because I'm using an automated process to do it and it's a littler
easier if I can do it that way.
Rob
RE: Dbo: Composite foreign key primary keys operator<, operator== - Added by Koen Deforche over 13 years ago
Hey Rob,
These operators are needed to be able to use the type as a key type for a std::map.
From http://www.cplusplus.com/reference/stl/map/:
Internally, the elements in the map are sorted from lower to higher key value following a specific strict weak ordering criterion set on construction.
http://en.wikipedia.org/wiki/Strict_weak_ordering
For your situation, or in general if you have multiple comparable values, then usually I do it like this (which is somewhat similar to how you order multi-digit numbers of multi-character strings):
if (tableA < other.tableA)
return true;
else if (tableA == other.tableA) {
// recursively do the same with tableB, tableC, ...
} else
return false;
Regards,
koen
RE: Dbo: Composite foreign key primary keys operator<, operator== - Added by Rob Farmelo over 13 years ago
Hi Koen,
OK, will do as stated in the tutorial... Thanks for the quick reply!
Rob