Question

I have an avl tree that houses objects that contain a string identifier.

I am having a user input a string and then I want to parse the tree to see if that user string matches any of the objects in the tree identifier. If there are no objects that have an identifier that matches the user's string, i want to create a object with the identifer set as the user's string. If the object with an identifier does match the user's input, I want to return the object to the user. At the moment I have two functions, one that returns a bool if the object exists in the tree already and one that returns the object to the console if it already exists in the tree. Is there a way to combine these two steps into one function? I am looking for something like:

if(...) // the item exists in the tree
{
    //return the object
}
else
{
    avltreeObject.insert(user_string);
}
Was it helpful?

Solution

Make the return type std::pair<bool, Object>.

if(/*the item exists in the tree*/)
{
   return std::make_pair(false, object);
}
else
{
   avltreeObject.insert(user_string);
   return std::make_pair(true, object);
}

OTHER TIPS

Something like this:

Object obj = avltreeObject.retrieve(user_string);
if( object != 0 ){
    return obj;
} else {
    avltreeObject.insert(user_string);
    return avltreeObject.retrieve(user_string);
}

The insert function might return the newly created object, so this can be improved.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top