C++ std::map::iterator 什么也没找到,但下标运算符 returns 引用映射值?

C++ std::map::iterator found nothing, yet subscript operator returns reference to mapped value?

可能做了一些非常愚蠢的事情,但我不明白为什么 find 找不到键等于 suppID 的元素。

然而,当我传递下标运算符 suppID 时,它 returns 是对其映射值的引用(暗示它找到了一些东西,对吗?)。

typedef std::map<SuppID, Supplement *> Supplement_t;

Supplement_t::iterator it = supplements.find(suppID);  //it = supplements.end()

cout << "Supplement name: " << supplements[suppID]->getName() << endl; // "Cytogainer"
... // Returns few of many other data members I tested...

这是因为 std::map 在使用 下标运算符 .

时为尚不存在的新键值插入默认值

如前所述here

1) Inserts value_type(key, T()) if the key does not exist. This function is equivalent to return insert(std::make_pair(key, T())).first->second; -key_type must meet the requirements of CopyConstructible. -mapped_type must meet the requirements of CopyConstructible and DefaultConstructible. If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.

为关联容器编写<时很容易出错。

最简单的方法是编写一个函数或方法,其中 returns 一个元组,可以是引用、值或混合。如果 foo.

则调用
friend bool operator<( self const& lhs, self const& rhs ){
  return lhs.foo()<rhs.foo();
}

如果你写 < 错了,你会得到非常疯狂的行为。