Hi I'm a student developing various abstract data types for learning purposes. I am trying to overload the subscript operator to look up the keys in these ADT's. I cannot avoid the case where my code inserts missing keys.
It is intended that when reading from these ADT's a return value of nullptr will indicate that the key was not found. I want my ADT's to add new keys only when writing or inserting. My code is incorrect in how it handles the following:
const char *x = tree["key"];
Here if "key" is not found I wish to avoid adding this key and return nullptr to indicate its absence. The key should only be added in the following situation:
tree["key"] = "x";
This is a very subtle bug. The following test returns true, but only because the value being tested is hash["key"].val (which happens to be null).
if (!x) printf("%s not found!\n", "key");
I believe this can be achieved through the use of const and have used the following signature.
char const *operator[](char *index) const;
This const overload is never invoked. Can somebody explain why this is the case and either an example signature which will behave properly (or an example which will force this overload to be evaluated). Here is my code:
#include <stdio.h>
#include <string.h>
class lookup {
lookup *left;
lookup *right;
char *key;
char *val;
public:
lookup(char *k) {
left = nullptr;
right = nullptr;
val = nullptr;
key = new char[strlen(k)+1];
strcpy(key, k);
}
~lookup() {
if (key) delete key;
if (val) delete val;
}
/* read/write access */
/* if the key does not exist, then create it */
char *&operator[](char *index) {
printf(" []= x\n");
int x = strcmp(index, key);
if (x < 0) {
if (left == nullptr) left = new lookup(index);
return (*left)[index];
}
if (x > 0) {
if (right == nullptr) right = new lookup(index);
return (*right)[index];
}
return val;
}
/* read only access */
/* if the key does not exist, then return nullptr (not found) */
char const *operator[](char *index) const {
printf(" x = *[]\n");
int x = strcmp(index, key);
if (x < 0) {
if (left == nullptr) return nullptr;
else return (*left)[index];
}
if (x > 0) {
if (right == nullptr) return nullptr;
else return (*right)[index];
}
return val;
}
};
int main(void) {
lookup tree("root");
/* this creates the key (which is not intended) */
const char *x = tree["key"];
if (!x) printf("%s not found!\n", "key");
/* only now should the key be created */
tree["key"] = "value";
return 0;
}