Reputation: 35
In the following code for a binary search tree:
template <class TKey>
class bst<TKey>::node *bst<TKey>::insert(node *T, TKey &key)
{
if (T == NULL) {
T = new node;
T->key = key;
} else if (T->key == key) {
cout << "key " << key << " already in tree" << endl;
} else {
int dir = T->key < key;
T->link[dir] = insert(T->link[dir], key);
}
return T;
}
I'm confused what the line
int dir = T->key < key;
is doing. I could understand int dir = T->key
, although of course that wouldn't make sense, but I've not seen the <
operator used in that way before. Any clues?
Upvotes: 3
Views: 10020
Reputation: 51832
If the operator isn't overloaded, than it has the usual meaning; it evaluates to either true
or false
. This is a bool
type, and therefore can be implicitly converted to an int
.
However, if TKey
is a class and overloads it, or there's a global overload, then we've no idea what it does unless we see the code.
Upvotes: 6
Reputation: 3939
Well, as the binary search tree stores values lesser than root on left and greater values on right, you need select which direction the insertion is gonna take place. To do this you are comparing the key with the current node's value. The result of this comparison is stored in dir variable. So if key is lesser than T's value, dir gets 1 which represents left side in the link[] that holds pointers to the left and right branches of the node T. And then insertion is done recursively with the left node of T. That is why you do a comparison there. Just to see whether we must insert the element to the right or left of the current node.
Upvotes: 0
Reputation: 681
The <
operator is a boolean comparison operator - i.e. it evaluates to 0
if the condition is false, and 1
if the condition is true. It's usually used in conditionals, but using the return value directly is perfectly valid. In this case, if the value of T->key
is less than the value of key
, dir
will be 1
otherwise dir
will be 0
.
Upvotes: 0
Reputation: 5920
<
returns 1 if the first operand is less than the second operand, or 0 otherwise.
Upvotes: 0
Reputation: 14039
T->key < key
is a condition. It will evaluate to either true
or false
.
If it evaluates to true
, dir
will get value 1
, otherwise it will get value 0
.
int dir = T->key < key;
is short form for writing
int dir;
if(T->key < key)
dir = 1;
else
dir = 0;
When a boolean
is assigned to an int
, it gets the value 0
or 1
corresponding to false
or true
.
Upvotes: 9