【问题标题】:using string_view to look up in unordered_map使用 string_view 在 unordered_map 中查找
【发布时间】:2020-07-30 01:05:11
【问题描述】:

说出下面的代码:

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++20 中,这可以通过 find() 成员函数进行一些设置:en.cppreference.com/w/cpp/container/unordered_map/find
  • 截至 2021 年 4 月 13 日,unordered_map 上的示例似乎gcc-trunkclang trunk 上起作用。那么在发布的版本中似乎并没有完全实现?

标签: c++ string unordered-map string-view


【解决方案1】:

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 constructor (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() );

【讨论】:

  • 我不是很懂上面的构造函数。我知道explicit 意味着没有从“char”到“basic_string”的隐式转换。这与我的问题有什么关系?谢谢! :)
  • 不存在从 string_view 到 string 的隐式转换构造函数。如果它存在,则将执行不需要的复制。无法从 string_view 构造字符串,因此 std::string&amp; operator[]( const std::string&amp; key ) 不可行。
猜你喜欢
  • 1970-01-01
  • 2016-06-02
  • 2021-06-21
  • 1970-01-01
  • 2016-11-15
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多