首页 > 解决方案 > 使用 string_view 在 unordered_map 中查找

问题描述

说下面的代码:

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.

我认为的目的string_view是在将字符串传递给函数时减少复制,对吗?

而且[]也是一种功能。为什么我不能将 string_view 传递给[]

谢谢!

标签: c++stringunordered-mapstring-view

解决方案


两者test_map[fake_str]test_map.at(fake_str)不起作用: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;

Key 类型是std::string,它没有隐式构造函数,std::string_view正如您所说的那样:“在将字符串传递给函数时减少复制”。

请参阅 std::basic_string 构造函数 (10)参考,查看关键字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() );

推荐阅读