简体   繁体   English

如果地图的键是指向字符串的指针,是否可以使用unordered :: map :: find?

[英]Is it possible to use unordered::map::find if the map's key is a pointer to string?

I have this map: 我有这张地图:

using namespace std; // just for readability

unordered_map<shared_ptr<string>, whatever_type> map;

Then a string comes from the outside. 然后一串从外面来。 Can I use find somehow? 我可以用某种方式find吗?

map.find(someInputString); // won't work, keys are wrapped by pointers

Is using a loop the only option? 使用循环是唯一的选择吗?

PS I am interested if there is some special signature of the find method, or another method to do this, to avoid a loop. PS我很感兴趣,如果有某种特殊的find方法签名,或者这样做的另一种方法,可以避免循环。

I was able to make it work with regular map. 我能够使其与常规地图一起使用。 Here is the code: 这是代码:

#include <map>
#include <string>
#include <memory>

struct PtrCompare {
    using is_transparent = bool;
    auto operator() (const std::shared_ptr<std::string>& lhs, const std::shared_ptr<std::string>& rhs) const {
        return *lhs < *rhs;
    }
    auto operator() (const std::shared_ptr<std::string>& lhs, const std::string& rhs) const {
        return *lhs < rhs;
    }
    auto operator() (const std::string& lhs, const std::shared_ptr<std::string>& rhs) const {
        return lhs < *rhs;
    }
};

std::map<std::shared_ptr<std::string>, int, PtrCompare>  my_hash;

auto check(const std::string& x) {
    return my_hash.find(x);
}

It uses the feature of transparent comparators, which is available on C++14. 它使用透明比较器的功能,该功能在C ++ 14上可用。 However, transparent comparators for unordered maps are only available with C++20, and thus, my solution doesn't work with unordered maps. 但是,无序映射的透明比较器仅在C ++ 20中可用,因此,我的解决方案不适用于无序映射。

The way to make it work with non-transparent comparator for unordered maps would be to still use custom hasher and comparator, which would compare arguments after dereferencing them, but create a shared pointer from a string you want to compare with, and find using this shared pointer. 使它与非透明比较器一起用于无序映射的方法是仍然使用自定义哈希器和比较器,它们将在取消引用后比较参数,但是从要与之比较的字符串中创建一个共享的指针,并找到使用它的方法。共享指针。 To me this solution is super ugly, so I am not suggesting this. 对我来说,这种解决方案非常丑陋,因此我不建议这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM