如何在boost::unordered_map中实现TryGetValue

how to implement TryGetValue in boost::unordered_map?

本文关键字:map 实现 TryGetValue unordered boost      更新时间:2023-10-16

C#中,我喜欢DictionaryTryGetValue方法,因为它允许我在一次调用中确定字典是否包含键和接收值,如果是的话:

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

如何与boost::unordered_map做同样的事情?

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