4

In C# i like TryGetValue method of Dictionary because it allows me in one call determine if dictionary contains key and receive value if so:

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

How should I do the same thing with boost::unordered_map?

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
Oleg Vazhnev
  • 23,239
  • 54
  • 171
  • 305

1 Answers1

7

Use 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";
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • just to doublecheck `m.find` will spent `log N` not `N`?? – Oleg Vazhnev May 01 '13 at 10:43
  • @javapowered An unordered_map<> is a hash table. The performance of a hash table can be anywhere between O(1) and O(n) depending on the hashing function and the distribution of your keys. If you want O(log n) then use std::map<>. – brian beuning May 01 '13 at 11:03
  • 2
    @javapowered The code above works for std::map<> also. Just change boost::unordered_map<> to std::map<>. – brian beuning May 01 '13 at 13:01