无法在 unordered_map 中找到密钥

unable to find key in unordered_map

创建了一个 unordered_map,键为 class 的 shared_ptr。定义了一个哈希函数,该函数根据 class 的数据成员创建哈希。我无法查找密钥。我看到在查找操作期间调用了散列方法。

// key to be stored in unordered_map
class data {
    public:
    char c;
    int i;
    data(char cc,int ii) {
       c=cc;i=ii;
    }
};

class myhash {
    public:
    size_t operator()(const std::tr1::shared_ptr<data> d1 ) const { 
        std::cout << ">" <<  std::tr1::hash<int>()(d1->c) << std::endl; 
        return std::tr1::hash<int>()(d1->c); 
    }
};

int main() {
    std::tr1::unordered_map<std::tr1::shared_ptr<data>, char, myhash> umap;
    //build map
    std::tr1::shared_ptr<data> d1( new data('A',1));
    umap[d1]='C';
    std::tr1::shared_ptr<data> d2( new data('B',1));
    umap[d2]='C';
    std::tr1::shared_ptr<data> d3(new data('C',1));
    umap[d3]='F';
    std::tr1::shared_ptr<data> d4(new data('D',1));
    umap[d4]='E';
    std::tr1::shared_ptr<data> d5(new data('E',1));
    umap[d5]='F';
    std::tr1::shared_ptr<data> d6(new data('F',1));
    umap[d6]='F';

    std::cout << "--------------" << std::endl;

    for(std::tr1::unordered_map<std::tr1::shared_ptr<data>, char,myhash>::iterator itr = umap.begin(); itr!=umap.end(); itr++) {
        if(itr->first->c == itr->second) 
            continue;
        std::tr1::shared_ptr<data> d11( new data(itr->second,0));
        std::tr1::unordered_map<std::tr1::shared_ptr<data>, char,myhash>::iterator index = umap.find(d11);
        if(index != umap.end()) <<<<----- its always null here. Not sure why
            index->first->i += itr->first->i;
        else
            std::cout << "NULL" << std::endl;
    }

    for(std::tr1::unordered_map<std::tr1::shared_ptr<data>, char,myhash>::iterator itr = umap.begin(); itr!=umap.end(); itr++) 
        std::cout << itr->first->c << " " << itr->first->i << std::endl;
}

您似乎定义了哈希函数,但没有定义相等函数。因此,您的 'identical' 键分类到相同的哈希桶中,但不会在映射中索引相同的值。

您需要为地图的键类型实现相等运算符或仿函数。否则,将使用 tr1::shared_ptr 的相等运算符,这不会满足您的需要。

例如,

struct myequal
{
  bool operator()(const std::tr1::shared_ptr<data>& lhs,
                  const std::tr1::shared_ptr<data>& rhs) const
  {
    return lhs->c == rhs->c;
  }
};

然后

std::tr1::unordered_map<std::tr1::shared_ptr<data>, char, myhash, myequal> umap;

查看工作示例 here