C++ 如何在boost::无序映射中实现TryGetValue?
在C++ 如何在boost::无序映射中实现TryGetValue?,c++,boost,boost-unordered,C++,Boost,Boost Unordered,在C#中,我喜欢TryGetValue方法Dictionary,因为它允许我在一次调用中确定Dictionary是否包含键,如果包含则接收值: Instrument instrument; if (isinId2Instrument.TryGetValue(isin_id, out instrument)) { // key exist, instrument contains value } else { // key doesn't exist } 我应该如何使用boost
C#
中,我喜欢TryGetValue
方法Dictionary
,因为它允许我在一次调用中确定Dictionary是否包含键,如果包含则接收值:
Instrument instrument;
if (isinId2Instrument.TryGetValue(isin_id, out instrument))
{
// key exist, instrument contains value
} else {
// key doesn't exist
}
我应该如何使用boost::unordered\u map
执行相同的操作?使用:
boost::无序映射::迭代器i=m.find(“hello”);
如果(i!=m.end())
{
std::cout首先只是双重检查m.find
将花费logn
而不是N
??@javapowered无序映射是一个哈希表。哈希表的性能可以在O(1)和O(N)之间的任意位置,具体取决于哈希函数和密钥的分布。如果需要O(logn)然后使用std::map。@上面的代码也适用于std::map。只需将boost::unordered_map更改为std::map即可。
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";
}