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

m6r*_*rco 1 c++ hash unordered-map

在我的程序中,如果我的无序映射中不存在某个键,我希望默认值将是 而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()

Jer*_*fin 8

一种可能性是为值类型创建一个小类:

class dproxy {
    double value_;
public:
    dproxy(double value = std::numeric_limits<double>::max())
    : value_{value} {}
    operator double &() { return value_; }
    operator double const &() const { return value_; }
};

std::unordered_map<Pair, dproxy> lFunction;
Run Code Online (Sandbox Code Playgroud)

默认构造的dproxy将被初始化为std::numeric_limits<double>::max(),并且 dproxy 将隐式转换为 a (对 a 的引用)double。如果您要进行大量隐式转换,则这可能会施加限制(例如,如果您有一些其他函数采用可以从 a 隐式构造的foo其他类型,则如果包含s 则可以工作,但如果它包含对象则不行,因为隐式转换序列只能使用一个用户定义的转换)。bardoublefoo(lFunction[baz]);lFunctiondoubledproxy

  • @m6rco 1)关于第一个问题,我编辑了上面的代码以在构造时初始化`dproxy`的`value_`成员。2) 关于“lFunction[Pair(3,3)] = 5”问题,“unordered_map”的“operator[]”将从“5”就地构造一个“dproxy”。检查 [cppreference](https://en.cppreference.com/w/cpp/container/unordered_map/operator_at) 和 [demo](https://godbolt.org/z/T9Efdhbvr)。 (2认同)