Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++17

I have

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

when I try

map.find("asdf"sv)

I get

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>> &'

is it possible to make map.find() compile with std::wstring_view or at least to do the search without constructing std::wstring?

like image 423
Alexey Starinsky Avatar asked Jan 11 '19 17:01

Alexey Starinsky


1 Answers

What you are trying to do is called "heterogeneous lookup" (basically, the type of the map and the type you're trying to use to lookup are different types). In C++20, thanks to P0919, we are going to get new overloads of unordered_map::find() that will allow what you're trying to do to work.

Until then, the only relevant overload takes, specifically, a Key const&. And basic_string's constructor from basic_string_view is explicit (see #10). So in C++17, you have to write:

map.find("asdf"s)

or

map.find(std::string("asdf"sv));
like image 133
Barry Avatar answered Oct 19 '22 21:10

Barry