c++ - 使用 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 传递给[]
?
谢谢!
解决方案
两者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() );
推荐阅读
- mongodb - 不同集合上的 Mongo db 事务
- android - ExoPlayer 同时播放多个视频
- c# - 派生类认为我的基类被删除了
- r - 将具有非常小的行总和的行合并到一个新的组合行中
- python - 时间数据与格式不匹配,尽管实际上它确实匹配
- macos-big-sur - 在 macOS Big Sur 中找不到 zsh 命令:ls
- embedded-linux - Linux 设备树:触摸控制器未通过 i2c 测试
- bash - Bash 脚本可以单独运行,但不能循环运行
- windows-server-2016 - 在 windows server 2016 上配置 NAS
- ios - 在 iphone 设备上运行 appc 时,在 iphone 设备上调用 xcodebuild 失败