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

jav*_*red 3 c++ boost boost-unordered

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

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

我该怎么做同样的事情boost::unordered_map

hmj*_*mjd 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";
}
Run Code Online (Sandbox Code Playgroud)

  • @javapowered上面的代码也适用于std :: map <>.只需将boost :: unordered_map <>更改为std :: map <>即可. (2认同)