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?
T->key < keyis a condition. It will evaluate to eithertrueorfalse.If it evaluates to
true,dirwill get value1, otherwise it will get value0.is short form for writing
When a
booleanis assigned to anint, it gets the value0or1corresponding tofalseortrue.