[英]c++ std::map<std::string, int> use at with std::string_view
Suppose I have a std::map<std::string, int>
.假设我有一个
std::map<std::string, int>
。 Is there any way to use its at
method with std::string_view
?有什么方法可以将其
at
方法与std::string_view
使用? Here is a code snippet:这是一个代码片段:
std::string_view key{ "a" };
std::map<std::string, int> tmp;
tmp["a"] = 0;
auto result = tmp.at(key);
Here is the output I have from clang 12.0这是我从 clang 12.0 获得的 output
error: no matching member function for call to 'at'
错误:没有匹配的成员 function 用于调用“at”
auto result = tmp.at(key);
自动结果 = tmp.at(key);
Three things are required for something like this to happen:发生这样的事情需要三件事:
The map's comparator must be a transparent comparator (requires C++14, but you're already using string_view
which is C++17, so this is a moot point).地图的比较器必须是透明比较器(需要 C++14,但您已经在使用
string_view
,即 C++17,所以这是一个有争议的问题)。
The at()
method must have an overload that participates in overload resolution when the container has a transparent comparator.当容器具有透明比较器时,
at()
方法必须具有参与重载解析的重载。
the parameter must be convertible to the map's key_type
.该参数必须可转换为地图的
key_type
。
Neither of these are true in your example.在您的示例中,这些都不正确。 The default
std::less
comparator is not a transparent comparator, there is no such overload for at()
, and std::string
does not have an implicit conversion from std::string_view
.默认的
std::less
比较器不是透明比较器, at()
没有这样的重载,并且std::string
没有来自std::string_view
的隐式转换。
There's nothing you can do about at()
, however you can do something about the comparator namely using the (transparent std::void
comparator) , and then use find()
instead of at()
, which does have a suitable overload:您对
at()
无能为力,但是您可以对比较器做一些事情, 即使用 (透明std::void
比较器) ,然后使用find()
而不是at()
,它确实有一个合适的重载:
#include <map>
#include <string>
#include <string_view>
int main()
{
std::string_view key{ "a" };
std::map<std::string, int, std::less<void>> tmp;
tmp["a"] = 0;
auto iter=tmp.find(key);
}
There is no implicit conversion from std::string_view
to std::string
, that is why you get a "no matching member function" error.没有从
std::string_view
到std::string
的隐式转换,这就是你得到“没有匹配的成员函数”错误的原因。 See: Why is there no implicit conversion from std::string_view to std::string?请参阅:为什么没有从 std::string_view 到 std::string 的隐式转换?
There is a std::string
constructor that will accept a std::string_view
as input, however it is marked as explicit
, so you will have to do this instead:有一个
std::string
构造函数将接受std::string_view
作为输入,但是它被标记为explicit
,所以你必须这样做:
auto result = tmp.at(std::string(key));
Same if you wanted to use the map's operator[]
with std::string_view
:如果您想将地图的
operator[]
与std::string_view
一起使用,则相同:
tmp[std::string(key)] = ...;
auto result = tmp[std::string(key)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.