-1

Say the following code:

unordered_map<string, int> test_map;
string_view fake_str = "Mike";
test_map[fake_str]; // does not work. No viable overloaded operator[] for type...
test_map.at(fake_str); // works.

I think the purpose of string_view is to reduce copy when passing string to function right?

And [] is also a function. Why I cannot pass string_view to []?

Thank you!

echo Lee
  • 191
  • 1
  • 2
  • 10
  • 2
    With C++20, this will be possible through the `find()` member function given a little setup: https://en.cppreference.com/w/cpp/container/unordered_map/find – Justin Jul 30 '20 at 01:24
  • As of 2021-04-13 the example on unordered_map seems to **only** function on `gcc-trunk` and `clang trunk`. So it seems that it isn't fully implemented in released versions? – Oliver Apr 13 '21 at 07:30

1 Answers1

1

Both test_map[fake_str] and test_map.at(fake_str) are not working: https://godbolt.org/z/EoP7bM

T& operator[]( const Key& key );
T& operator[]( Key&& key );
T& at( const Key& key );
const T& at( const Key& key ) const;

The Key type is std::string, that does not have implicit constructor from std::string_view by the exact reason as you said: "to reduce copy when passing string to function".

See the std::basic_string constructor (10) reference, look at the keyword explicit.

template < class T >
explicit basic_string( const T& t, const Allocator& alloc = Allocator() );

template < class T >
explicit constexpr basic_string( const T& t,
                                 const Allocator& alloc = Allocator() );
273K
  • 29,503
  • 10
  • 41
  • 64
  • I don't really understand the constructor above. I know the ```explicit``` means that no implicit conversion from "char" to "basic_string". How is that related to my problem? Thx! :) – echo Lee Jul 30 '20 at 03:45
  • No implicit converting constructor from string_view to string exist. If it would exist then unneeded copy would be performed. String can't be constructed from string_view, thus `std::string& operator[]( const std::string& key )` is not viable. – 273K Jul 30 '20 at 05:37