如何在boost::unordered_map中实现TryGetValue?

4

C# 中,我喜欢使用 DictionaryTryGetValue 方法,因为它可以一次性确定字典是否包含键并获取相应的值:

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

我该如何使用boost::unordered_map实现同样的功能呢?
1个回答

7

使用 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";
}

只是为了确认一下,m.find 的时间复杂度应该是 log N 而不是 N 吧? - Oleg Vazhnev
@javapowered 一个 unordered_map<> 是哈希表。哈希表的性能取决于哈希函数和键的分布,可以在 O(1) 和 O(n) 之间。如果想要 O(log n),则使用 std::map<>。 - brian beuning
2
@javapowered 上面的代码也适用于 std::map<>。只需将 boost::unordered_map<> 更改为 std::map<> 即可。 - brian beuning

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接