0
I have a class of a B tree that has a search method, the search method must return a reference to the value associated with the search key, so the user can change it if he wants, this is a pair used in the tree:
template<class Key, class Value>
class Pair{
public:
Pair(){
key = Key();
value = Value();
}
Pair(Key key, Value value){
this->key = key;
this->value = value;
}
Key key;
Value value;
};
The problem is I don’t know what to do when the search finds nothing. So what I want is a method that can return a reference to something and somehow inform whether the value is valid or not, there are some ways to do this, I’ll list the ones I found and why I don’t want to use them:
- Fire an exception: I think it’s a very exaggerated action for a simple answer, and honestly I think it’s outside the scope of exceptions that should only report errors.
- Put an additional parameter that informs whether the value is valid or not: good and simple, but as I said I wanted a method with a single answer, I will equip this method if I do not find another.
- Use an additional structure that stores the reference and tells whether it is valid or not: I found this method interesting, the problem is that the object within the structure is a reference and should point somewhere even when the search does not return anything.
If you can tell me how to fix this I appreciate.
Related or duplicate: http://answall.com/q/21767/101 or if not, maybe it is based on opinion.
– Maniero
Well connected, I don’t know if it’s duplicate but it’s almost, hehe, anyway thanks for the link, I’ll opt for the multiple returns. The question was based on multiple "opinions" but I came here in search of a definitive answer, so I listed the "opinions" that were possible, but I think I left open to new possibilities :s
– ProgramandoMil
I don’t think it’s a duplicate either, but I kind of agree with @bigown that it’s based on opinion. I would say that option 1 is easy to argue against in a concrete way, but options 2 and 3 are equally feasible and will depend essentially on what each one prefers. Particularly, I would choose the 3 because it does exactly as you wish: it indicates the failure of the result in a single place (in the class itself
Pair
). On the object need to "point somewhere", creates an empty reference, since it does not matter.– Luiz Vieira
Actually, I don’t think there’s any unique and more recommended way to do this, I said I would use the second option but I will use the third (with a
std::pair
), because in the case of invalid reference the user can keep further away from it, just it check thepair.second
to know whether or not to use thepair.first
– ProgramandoMil