【问题标题】:Is it possible to use unordered::map::find if the map's key is a pointer to string?如果地图的键是指向字符串的指针,是否可以使用 unordered::map::find?
【发布时间】:2019-09-13 20:51:58
【问题描述】:

我有这张地图:

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

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

附:如果find 方法或其他方法可以避免循环,我很感兴趣。

【问题讨论】:

  • 我强烈建议反对使用shared_ptr's 作为键。我无法想象为什么它可能是可取的。
  • @SergeyA 如果字符串很大,而且它们也存储在其他地方怎么办
  • 您可以使用带有自定义哈希码和比较器的unordered_map。我没有看到其他快速工作的方法。我从来没有这样做过,但可能你必须为键定义自己的包装类。
  • @SergeyA 有道理,但希望最后死去 :-) 这就是我问的原因
  • 您可能必须使用自定义哈希函数和自定义比较函数来取消引用指针。您可能希望使用透明分配器。共享指针也让它变得非常奇怪,你能改变设计以使用普通的非拥有指针吗?

标签: c++ pointers unordered-map


【解决方案1】:

我能够使其与常规地图一起使用。代码如下:

#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,因此,我的解决方案不适用于无序映射。

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

【讨论】:

  • 你的意思是透明的比较器吗?
  • 哇。我对 C++ 的了解如此之低,以至于我还无法理解这个解决方案(及其性能特征)。但是,谢谢!我希望我能尽快提高我的知识以理解并可能尽快使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-19
  • 2011-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多