簡體   English   中英

返回False或Value C ++

[英]Return False or Value C++

我有一個avl樹,其中包含包含字符串標識符的對象。

我有一個用戶輸入一個字符串,然后我想解析該樹以查看該用戶字符串是否與樹標識符中的任何對象匹配。 如果沒有具有與用戶字符串匹配的標識符的對象,我想創建一個將標識符設置為用戶字符串的對象。 如果帶有標識符的對象確實與用戶輸入匹配,我想將對象返回給用戶。 目前,我有兩個函數,如果樹中已經存在該對象,則返回一個布爾值;如果樹中已經存在該對象,則將一個返回對象到控制台。 有沒有辦法將這兩個步驟組合為一個功能? 我正在尋找類似的東西:

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

使返回類型為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);
}

像這樣:

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

insert函數可能會返回新創建的對象,因此可以對其進行改進。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM