2013-02-06 20 views
-3

我有一個類將提供一個函數看到的一個項目,它將返回false第一次看到某個字符串,但每次後true當相同的字符串被調用。C++跟蹤一個項目,然後返回

class Tracking 
{ 
    ... 
public: 
    bool itemseen(const char* str) 
    { 
     .. 
    }  
}; 
+2

有一個問題在這裏? –

+0

這個問題沒有顯示研究工作。 – Johnsyweb

回答

2

這聽起來像你需要/想任何一個std::set<std::string>std::unordered_set<std::string>

當您收到一個項目時,嘗試將其插入到[unordered_]集合中。檢查返回值以查看成功與否。

請注意,首先搜索該項目,然後嘗試插入,如果它不存在是相當浪費。通常你只是想嘗試插入,然後檢查返回值,看看是否能成功:

class whatever { 
    std::set<std::string> strings; 
public: 
    bool itemseen(std::string const &input) { 
     return !strings.insert(input).second; 
    } 
}; 

如果你做一個搜索,然後再插入,你強迫它的時候搜索的集合兩次/如果它插入一個新的對象。使用返回值可以讓您只搜索一次。 IOW,你可以預計它會快兩倍(雖然緩存可能會使第二次搜索更快,所以測量的差異可能會比這小)。

+1

雖然你可能不想在'set'中存儲'const char *'s。 – Johnsyweb

+0

啊,我沒有想到這個意圖。 – chris

+1

@Johnsyweb:好點 - 澄清。 –

2

最簡單的方法是使用STL:

#include <set> 
#include <string> 

std::set<std::string> seen; 

bool itemseen(const char* str) 
{ 
    if (seen.find(str) == seen.end()) 
    { 
    seen.insert(str); 
    return false; 
    } 

    return true; 
} 
+1

如果你有點混淆。找到它後插入它。 – chris

+0

相反的比較,然後當我試圖修復它時,SO正好下降。雖然修復了它。 – Jack

相關問題