简体   繁体   English

返回False或Value C ++

[英]Return False or Value C++

I have an avl tree that houses objects that contain a string identifier. 我有一个avl树,其中包含包含字符串标识符的对象。

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);
}

Make the return type std::pair<bool, Object> . 使返回类型为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);
}

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. insert函数可能会返回新创建的对象,因此可以对其进行改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM