2013-05-01 75 views
3

C#我喜歡的DictionaryTryGetValue方法,因爲它可以讓我在一個呼叫確定字典包含鍵和接收值,如果這樣:如何在boost :: unordered_map中實現TryGetValue?

Instrument instrument; 
if (isinId2Instrument.TryGetValue(isin_id, out instrument)) 
{ 
    // key exist, instrument contains value 
} else { 
    // key doesn't exist 
} 

我應該怎麼做boost::unordered_map同樣的事情?

回答

6

使用boost::unordered_map::find()

boost::unordered_map<std::string, int>::iterator i = m.find("hello"); 
if (i != m.end()) 
{ 
    std::cout << i->first << "=" << i->second << "\n"; 
} 
else 
{ 
    std::cout << "Not found\n"; 
} 
+0

只是雙檢'm.find'將花費'登錄N'不'N'? – javapowered 2013-05-01 10:43:13

+0

@javapowered unordered_map <>是一個哈希表。散列表的性能可以在O(1)和O(n)之間的任何位置,具體取決於散列函數和密鑰的分佈。如果你想O(log n),然後使用std :: map <>。 – 2013-05-01 11:03:19

+0

@brianbeuning我需要log N的平均值。 – javapowered 2013-05-01 11:47:56

相關問題