std :: unordered_map :: find是否使用与Key类型不同的类型? [英] std::unordered_map::find using a type different than the Key type?

查看:191
本文介绍了std :: unordered_map :: find是否使用与Key类型不同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 unordered_map ,它使用字符串类型作为键:

I have an unordered_map that uses a string-type as a key:

std::unordered_map<string, value> map;

提供了 std :: hash 专业化 string ,以及合适的
operator ==

A std::hash specialization is provided for string, as well as a suitable operator==.

现在我还有一个字符串视图类,它是指向现有字符串的弱指针,避免了堆分配:

Now I also have a "string view" class, which is a weak pointer into an existing string, avoiding heap allocations:

class string_view {
    string *data;
    size_t begin, len;
    // ...
};  

现在,我希望能够使用<$检查地图中是否存在键c $ c> string_view 对象。不幸的是, std :: unordered_map :: find 接受 Key 参数,而不是通用的 T 参数。

Now I'd like to be able to check if a key exists in the map using a string_view object. Unfortunately, std::unordered_map::find takes a Key argument, not a generic T argument.

(当然,我可以将一个提升为字符串

(Sure, I can "promote" one to a string, but that causes an allocation I'd like to avoid.)

我想要的是类似

template<class Key, class Value>
class unordered_map
{
    template<class T> iterator find(const T &t);
};

这需要 operator ==(T,Key) std :: hash< T>()进行适当定义,并将迭代器返回到匹配值。

which would require operator==(T, Key) and std::hash<T>() to be suitably defined, and would return an iterator to a matching value.

有什么解决方法吗?

推荐答案

P0919R2对无序容器的异构查找已在C语言中合并++ 2a的工作草案!

P0919R2 Heterogeneous lookup for unordered containers has been merged in the C++2a's working draft!

摘要似乎很合适我原来的问题:-)

The abstract seems a perfect match w.r.t. my original question :-)


摘要



该提案增加了异构查询支持到C ++标准库中的无序关联容器。结果,当提供不同(但兼容)的类型作为成员函数的键时,不需要创建临时键对象。

Abstract

This proposal adds heterogeneous lookup support to the unordered associative containers in the C++ Standard Library. As a result, a creation of a temporary key object is not needed when different (but compatible) type is provided as a key to the member function. This also makes unordered and regular associative container interfaces and functionality more compatible with each other.

通过本文提出的更改,以下代码将可以正常工作,而不会影响性能:

With the changes proposed by this paper the following code will work without any additional performance hits:

template<typename Key, typename Value>
using h_str_umap = std::unordered_map<Key, Value, string_hash>;
h_str_umap<std::string, int> map = /* ... */;
map.find("This does not create a temporary std::string object :-)"sv);


这篇关于std :: unordered_map :: find是否使用与Key类型不同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆