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

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

我有这张地图:

using namespace std; // just for readability

unordered_map<shared_ptr<string>, whatever_type> map;

然后从外面传来一根绳子。我可以以某种方式使用 find 吗?

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

使用循环是唯一的选择吗?

P.S。我感兴趣的是 find 方法是否有一些特殊的签名,或者其他方法可以避免循环。

我能够让它与普通地图一起工作。这是代码:

#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);
}

它使用了 C++14 上可用的透明比较器的特性。但是,无序映射的透明比较器仅适用于 C++20,因此,我的解决方案不适用于无序映射。

让它与无序映射的非透明比较器一起工作的方法是仍然使用自定义哈希器和比较器,它们会在取消引用参数后比较参数,但是从要与之比较的字符串创建共享指针, 并找到使用这个共享指针。对我来说这个解决方案非常丑陋,所以我不建议这样做。