2

I have std::unordered_map<std::string, MyType>.

I get a char const* key, which I need to look up. Is there anyway to do it without constructing std::string(key) to avoid memory copy?

As I understand, C++20 allows it:

std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::find :

      template<class K> iterator find( const K& x );

So I can use std::string_view as K. Any way to do it in C++17?

user2052436
  • 4,321
  • 1
  • 25
  • 46
  • Of course you can. Either use the std::string_view once argument constructor, or let the compiler do it automatically for you, by calling `std:::unordered_map<>::find(your_char_ptr); Recent std libraries wlilll correctly call the string_view constructor from there. – Michaël Roy Nov 09 '20 at 04:10
  • 2
    @MichaëlRoy _"Of course"_ [Are you sure?](http://coliru.stacked-crooked.com/a/ff95fab76bf3d65e) – Asteroids With Wings Nov 09 '20 at 04:12
  • Does this answer your question? [C++ unordered\_map lookup without constructing string](https://stackoverflow.com/questions/49709548/c-unordered-mapstring-lookup-without-constructing-string) – Asteroids With Wings Nov 09 '20 at 04:13
  • 1
    @MichaëlRoy Wouldn't `mymap.find(your_cchar_ptr)` be equivalent to `mymap.find( std::string(your_cchar_ptr) )`? – user2052436 Nov 09 '20 at 04:13
  • I honestly doubt that you can, but, if I might ask, why are you using `std::string`s in the first place here? –  Nov 09 '20 at 04:34
  • @AsteroidsWithWings Thank you. I've checked it out, and youu're right. c++ std::unordered_map::find() does not have an overload that taes a string_view. This makes this question moot. Please dieregard my previous comment. I was wrong. I will not remove it so the rest of the conversation makes sense. Code at https://godbolt.org/z/1s4zxv – Michaël Roy Nov 09 '20 at 04:36
  • @xxh I am not understanding your question. If my keys are strings, what other type could I use for them? – user2052436 Nov 09 '20 at 18:46
  • @user2052436 `std::string_view`s do not require any extra memory allocations, they're what I've used for `std::map`s before. But I understand if changing the actual map itself isn't allowed, or a viable option. –  Nov 09 '20 at 18:47

0 Answers0