gpt4 book ai didi

c++ - std::unordered_map::find 使用与 Key 类型不同的类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:58 26 4
gpt4 key购买 nike

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

std::unordered_map<string, value> map;

A std::hashstring 提供特化, 以及ASA适合operator== .

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

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

现在我希望能够使用 string_view 检查 map 中是否存在键目的。不幸的是,std::unordered_map::find需要 Key参数,不是通用的T争论。

(当然,我可以将一个“提升”为 string,但这会导致我想避免的分配。)

我本来喜欢的是类似的东西

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

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

有什么解决方法吗?

最佳答案

P0919R2 Heterogeneous lookup for unordered containers已合并到 C++2a 的工作草案中!

摘要似乎与 w.r.t. 完美匹配。我原来的问题:-)

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

关于c++ - std::unordered_map::find 使用与 Key 类型不同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52938862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com