I need to write a dictionary in c There is a function that returns the value of a dictionary by key, but if there is no value, then I want to return something like NULL. The value 0 is not suitable because it could be the value of some other key. What can i use instead of 0?
TValue getByKey(TKey key)
{
for (unsigned i = 0; i < this->pairs.size(); i )
{
if (this->pairs[i].key == key)
return this->pairs[i].value;
}
return NULL;
}
if I use NULL it gives me a warning (g compiler):
warning: converting to non-pointer type 'int' from NULL
CodePudding user response:
NULL
is specifically a value for pointers. If the object that you return is not a pointer (or a smart pointer), then returning NULL
is wrong.
If you return an int
, then you can only return a value that int
can represent, i.e. 0 or 1 or 2 ...
If you want to return a value that represents "no value", then you can return instance of std::optional
template instead. Example:
std::optional<TValue> getByKey(TKey key)
{
// ...
return std::nullopt;
}
P.S. You can replace your loop that implements linear search with the standard function std::find
.
P.P.S If you have many values, then may want to consider using another data structure that has faster key lookup such as std::unordered_map
.
P.P.P.S Don't use NULL
for pointers either. It has been obsoleted by nullptr
.