如何在 std::unordered_map<std::wstring, T> 中通过 std::wstring_view 类型的键查找?

How to find by a key of type std::wstring_view in std::unordered_map<std::wstring, T>?

提问人:Alexey Starinsky 提问时间:1/12/2019 最后编辑:Alexey Starinsky 更新时间:1/12/2019 访问量:976

问:

我有

std::unordered_map<std::wstring, std::vector<unsigned>> map;

当我尝试时

map.find("asdf"sv)

我得到

error C2664: 'std::_List_const_iterator<std::_List_val<std::_List_simple_types<_Ty>>> std::_Hash<std::_Umap_traits<_Kty,std::vector<unsigned int,std::allocator<unsigned int>>,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>::find(const std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>> &) const': cannot convert argument 1 from 'std::wstring_view' to 'const std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>> &'

是否可以使用 std::wstring_view 进行 map.find() 编译,或者至少在不构造 std::wstring 的情况下进行搜索?

++ 的 C++17

评论

3赞 Hatted Rooster 1/12/2019
AFAIK并非没有构造一个,请参阅:stackoverflow.com/a/34597313/1870760wstring
0赞 Alexey Starinsky 1/12/2019
@SombreroChicken至少可以在 C++ 20 中使用 std::wstring_view 编译 map.find(),请参见 3,4 en.cppreference.com/w/cpp/container/unordered_map/find

答:

7赞 Barry 1/12/2019 #1

您尝试执行的操作称为“异构查找”(基本上,映射的类型和您尝试用于查找的类型是不同的类型)。在 C++20 中,多亏了 P0919,我们将获得新的 unordered_map::find() 重载,这将允许您尝试执行的操作。

在此之前,唯一相关的重载具体来说是一个 .而 basic_string_view 的构造函数是(参见 #10)。所以在 C++17 中,你必须写:Key const&basic_stringexplicit

map.find("asdf"s)

map.find(std::string("asdf"sv));