2013-05-01 31 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

相关问题