【问题标题】:using unordered_set custom hash and find使用 unordered_set 自定义哈希并找到
【发布时间】:2019-06-13 23:39:58
【问题描述】:

我的 unordered_set 有一个哈希函数,我想使用 set 的查找功能,但我遇到了错误。如何通过自定义哈希函数使用 set 的查找功能?

我想在无序集中存储一对,为此我有一个简单的哈希函数,只是尝试使用查找功能,但它会引发错误。以下是错误:

solution.cpp:在成员函数 anagramMappings Line 22: Char 33: error: no matching function for call to 'std::unordered_set, Solution::SimpleHash>::find(__gnu_cxx::__alloc_traits, int>::value_type&)' 它 = mySet.find(A[i]); ^

struct SimpleHash {
    size_t operator()(const std::pair<int, int>& p) const {
    return hash<int>()(p.first) ^ hash<int>()(p.second);
    }
};

vector<int> anagramMappings(vector<int>& A, vector<int>& B) {

    vector<int> res;
    unordered_set<pair<int,int>, SimpleHash> mySet;
    unordered_set<pair<int,int>, SimpleHash>::iterator it;

    for(int i=0; i < B.size(); i++) {
        mySet.insert(make_pair(B[i],i));
    }

    for(int i=0; i<A.size(); i++) {

        it = mySet.find(A[i]);
        if(it != mySet.end()) {
            res.push_back(it->second);
        }
    }

    // for(it = mySet.begin(); it != mySet.end(); it++) {
    //     cout << it->first << " " << it->second << endl;
    // }

    return res;
}

当使用 mySet.find(key) 时,它应该返回 pair 的第一个元素

【问题讨论】:

    标签: stl find c++17 hashset unordered-set


    【解决方案1】:

    unordered_set&lt;T&gt;::find() 想要 T 作为参数 - 在这种情况下,pair&lt;int, int&gt;。您正在传递一个 int

    您可能需要考虑 std::unordered_map,因为您似乎希望将一个 int 视为查找键,而将另一个视为与该键关联的值。

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 2020-03-26
      • 2012-11-09
      • 2018-06-07
      • 2013-08-07
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      相关资源
      最近更新 更多