小编m6r*_*rco的帖子

如果键不存在,设置无序映射的默认值

在我的程序中,如果我的无序映射中不存在某个键,我希望默认值将是 而std::numeric_limits<double>::max()不是 0。

我的代码如下所示:

class Pair
{
public:
   Graph::NodeId node;
   bitset<64> bits;

   Pair(Graph::NodeId node1, double bits1)
   {
       node = node1;
       bitset<64> temp(bits1);
       bits = temp;
   }

};

bool operator==(const Pair &P1, const Pair &P2)
{
   return P1.node == P2.node && P1.bits == P2.bits;
}

template <>
struct std::hash<Pair>
{
std::size_t operator()(const Pair &pair) const noexcept
{
  std::hash<decltype(pair.node)> ihash;
  std::hash<decltype(pair.bits)> bhash;
  return ihash(pair.node) * 31 + bhash(pair.bits);
}
};

unordered_map<Pair, double> lFunction;
Run Code Online (Sandbox Code Playgroud)

因此,如果我想访问该元素lFunction[Pair(3,3)]并且键不存在,则应该存在 value std::numeric_limits<double>::max()

c++ hash unordered-map

1
推荐指数
1
解决办法
1225
查看次数

标签 统计

c++ ×1

hash ×1

unordered-map ×1