std::unordered_map<Foo, Bar> 测试特定的 Foo 键是否存在

std::unordered_map<Foo, Bar> test if specific Foo key is present

我有一个 Foo 对象的无序映射,我想有效地测试键集是否包含具有给定 ID 的 Foo 对象。

一种方法是构造一个 Foo 对象并将其 id 设置为查询值,但我想知道是否有更优雅的方法来实现此目的(可能使用不同的数据结构)?

class Foo {

    public: 
        int id;
};

namespace std
{
    template<> 
    struct hash<Foo> {
       std::size_t operator()(Foo const& f) const {
            return std::hash<int>()(f.id);
       }
    };

    template<>
    struct equal_to<Foo> {
        bool operator()(const Foo &lhs, const Foo &rhs) const {
            return lhs.id == rhs.id;
        }
    };
}


int main() {

  unordered_map<Foo, int> dict;

  Foo f;
  f.id = 123;

  dict[f] = 1;

  //How to test if Foo object with id x is present in dict? 

}

不,没有比使用您要使用当前集合测试的 id 创建 Foo 对象更有效的方法了。您正在 "stuck" 使用您最初选择的密钥类型。

如果您想通过 int 属性 为字典编制索引,请考虑将 属性 作为键并将 Foo 对象作为值的一部分。 (在这种情况下可能看起来像 unordered_map<int, pair<Foo, int>>。)