【问题标题】:Custom structure as key in unordered_map自定义结构作为 unordered_map 中的键
【发布时间】:2020-08-15 17:09:44
【问题描述】:

我想使用结构 Item 作为 unordered_map 中的键 我实现了哈希和相等操作的结构。 但我有一个错误

hashtable_policy.h:1384:16:错误:不匹配调用 '(const ItemHash) (const Item&)' solution.cpp:28:12:注意:候选:'size_t ItemHash::operator()(Item)' 32 | size_t operator()(Item item) { solution.cpp:28:12:注意:将 'const ItemHash*' 作为 'this' 参数传递会丢弃限定符

我该如何解决这个错误?

我的代码

vector<int> get_key(const string& s) {
    vector<int> res(26, 0);
    for (int i = 0; i < s.size(); ++i) {
        int pos = s[i] - 'a';
        res[pos]++;
    }
    return res;
}

struct Item {
    vector<int> v;
    
    Item(const vector<int>& vec) : v(vec) {}
    bool operator==(Item other) {
        if (v.size() != other.v.size()) {
            return false;
        }
        for (int i = 0; i < v.size(); ++i) {
            if (v[i] != other.v[i]) {
                return false;
            }
        }
        return true;
    }
};

struct ItemHash {
    size_t operator()(Item item) {
        auto vec = item.v;
        size_t seed = vec.size();
        for(auto& i : vec) {
            seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
        }
        return seed;
    }
};

struct ItemEqual {
    bool operator()(Item item1, Item item2) {
        return item1 == item2;
    }  
};

vector<vector<int> > Solution::anagrams(const vector<string> &A) {
    vector<vector<int>> res;
    unordered_map<Item, vector<int>, ItemHash, ItemEqual> hash; // hash_key, vector of indexes
    for (int i = 0; i < A.size(); ++i) {
        Item item = Item(get_key(A[i]));
        hash[item].push_back(i);
    }
    for (const auto& i : hash) {
        res.push_back(i.second);
    }
    return res;
}

【问题讨论】:

  • 您可能还应该通过const &amp; 传递Item。所以,size_t operator()(const Item &amp;item) const {bool operator()(const Item &amp;item1, const Item &amp;item2) const {

标签: c++ stl


【解决方案1】:

你需要const-qualify ItemHash::operator()(Item),即,

struct ItemHash {
    size_t operator()(Item item) const
    //                            ^^^^ here
    {
       // as before...
    }

请注意,正如 @JeJo 在 cmets 中指出的那样,您需要对 ItemEqual 进行相同的修复。

【讨论】:

  • 感谢您的回答!
猜你喜欢
  • 1970-01-01
  • 2013-06-05
相关资源
最近更新 更多