Reference return with possibility of invalid object

0

I have a class of a tree B that has a search method, the search method should return a reference to the value associated with the searched key, so the user can change it if you want, 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 that I do not know what to do when the search does not find anything. So what I want is a method that can return a reference to something and somehow inform if the value is valid or not, there are some ways to do this, I'll list the ones I've found and why I do not want to use them: / p>

  • Triggering an exception: I think it is a very exaggerated action for a simple answer, and honestly I think it escapes from the scope of exceptions that should only report errors.
  • Add 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 adopt this method if I can not find another one.
  • Use an additional structure that holds the reference and informs whether it is valid or not: I find this method interesting, the problem is that the object inside the structure is a reference and should point somewhere, even when the search returns nothing.
  • If you can tell me how to solve this, I thank you.

        
    asked by anonymous 05.05.2016 / 04:05

    1 answer

    0

    I can think of these two simple componteiros solutions.

    template<typename K, typename V>
    V *find(K key)
    {
        ...
    }
    int *v = find(key);
    if(v) ...
    

    Or

    template<typename K, typename V>
    bool find(K key, V **value)
    {
        ...
    }
    
    int *v;
    if(find(10, &v)) ...
    

    A better solution would be to create an iterator: link

        
    15.07.2016 / 05:13