unordered_map:带有一对std :: string_view的std :: string的查找对
给定一个在一对字符串上键入的hashmap,例如:
std :: unordered_map< std :: pair< string,string>,int> mymap;
如何使用一对std :: string_view(例如:
std::string s = "I'm a string";
std::string s2 = "I'm also a string";
std::string_view sv(s);
std::string_view sv2(s2);
myMap.find(std::make_pair(sv, sv2));
我想我需要在某个地方定义自己的比较器)进行查找,但是我不确定从哪里开始。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用C ++ 20年代的异质查找,可以完成此操作(请参阅
unordered_map :: find()
)。为此,必须定义一个hash函数和平等函数,例如:
地图的类型必须更改为
std :: unordered_map&lt&std :: pair&lt&lt&std :: string :: std :: std ::字符串>,int,hash,quare>
,以便使用定义的函数。find()
现在按预期工作:可以使用在这里
With C++20's heterogeneous lookups this can be done (see documentation of
unordered_map::find()
). For this to work a hash functor and a equality functor have to be defined, e.g.:The type of the map then has to be changed to
std::unordered_map<std::pair<std::string, std::string>, int, hash, equal>
in order to use the defined functors.find()
now works as intended:The implementation can be played with here
由于您正在使用
unordered_map
,因此您需要为您的自定义密钥类型提供hash函数
和keyequal
,而不是键类型的比较器仅通过排序的容器(例如set/map
)或排序的容器适配器(PRIRISITION_QUEUE
)才需要。在您的示例中,密钥类型为
pair&lt; string_view,string_view&gt;
。std :: Pair
类型已经定义了其==
运算符,但它不提供哈希功能。因此,我们只需要为std :: Pair
类型定义哈希函数。幸运的是,STL已经为std :: String_view
提供了哈希模板专业化,这使我们的任务变得更加容易。这是代码:输出是:
Since you are using
unordered_map
, then you need to provideHash function
andKeyEqual
for your custom key type, not the comparator for the key type which is needed only by sorted containers (such asset/map
) or sorted container adapter (priority_queue
).In your example, the key type is
pair<string_view, string_view>
. Thestd::pair
type already defines its==
operator, but it provides no hash function. So we only need to define a hash function for thestd::pair
type. Fortunately, STL already provides the hash template specialization forstd::string_view
, which makes our task much easier. Here is the code:output is: