【问题标题】:unordered_map for <Pointer, String> in C++C++ 中 <Pointer, String> 的 unordered_map
【发布时间】:2016-04-12 09:02:13
【问题描述】:

我正在尝试为&lt;xml_node*,string&gt; 对创建一个unordered_map,其中xml_node 是来自pugixml 库的xml 元素,我希望将其指针存储为键。我已经这样声明了地图:

unordered_map<xml_node*,string> label_hash;

现在insert 功能运行良好。但每当我尝试find 来自散列的一个元素时:

string lb = string(label_hash.find(node));

我收到以下错误:

no matching function for call to ‘std::basic_string<char>::basic_string(std::_Hashtable<pugi::xml_node*, std::pair<pugi::xml_node* const, std::basic_string<char> >, std::allocator<std::pair<pugi::xml_node* const, std::basic_string<char> > >, std::_Select1st<std::pair<pugi::xml_node* const, std::basic_string<char> > >, std::equal_to<pugi::xml_node*>, std::hash<pugi::xml_node*>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, false, false, true>::iterator)’|

现在我需要为地图实现哈希函数和相等函数吗?我试图按如下方式实现它们,但它不起作用:

struct hashing_func {
    unsigned long operator()(const xml_node* key) const {
        uintptr_t ad = (uintptr_t)key;
        return (size_t)((13 * ad) ^ (ad >> 15));
        //return hash<xml_node*>(key);
    }
};

struct key_equal_fn {
    bool operator()(const xml_node* t1, const xml_node* t2) const {
        return (t1 == t2);
    }
};

我对 C++ 有点陌生,所以能提供一点帮助会很棒!

【问题讨论】:

    标签: c++ xml dictionary unordered-map pugixml


    【解决方案1】:

    请阅读文档:unordered_map::find 返回一个迭代器到pair&lt;xml_node const*, string&gt;。 (您不能将它传递给 string 构造函数。)而是这样做:

    auto iterator = label_hash.find(node);
    
    if (iterator != label_hash.end()) { // `.find()` returns `.end()` if the key is not in the map
        string& lb = iterator->second; // The `&` is optional here, use it if you don't want to deepcopy the whole string.
        // use lb
    }
    else {
        // key not in the map
    }
    

    【讨论】:

    • 谢谢!工作完美!另一个查询,如何测试密钥(此处的指针)是否存在于哈希中?我尝试了一个不在哈希中的指针并导致了段错误
    • 另请注意,您不应使用指向 xml_node 的指针作为键 - 直接使用 xml_node。你可以像这样散列它:node.hash_value()
    • 指针作为映射键的用途是有效的,但是是的,使用非指针键类型更常见。
    【解决方案2】:

    我写了一个小测试程序:

    #include <unordered_map>
    #include <string>
    namespace pugi
    { 
      struct xml_node {};
    }
    
    int main()
    {
      std::unordered_map<pugi::xml_node*, std::string> mymap;
    
      pugi::xml_node n1;
    
      mymap.emplace(&n1, "foo");
    
      auto i = mymap.find(&n1);
    
      i->second;
    
      return 0;
    
    }
    

    这编译完美,表明问题不在于使用指针作为映射键,不在于缺少自定义比较器,也不在于缺少哈希函数。

    unordered_map::find 返回一个迭代器——它指向一个键/值对。

    【讨论】:

    • 谢谢!所以 i->first 给出了键,而 i->second 给出了值对吗?
    猜你喜欢
    • 2021-10-01
    • 2017-12-02
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-08
    相关资源
    最近更新 更多