假设我有一个 std::map<std::string, int>
.有什么办法可以使用它的at
方法与 std::string_view
?这是一个代码片段:
std::string_view key{ "a" };
std::map<std::string, int> tmp;
tmp["a"] = 0;
auto result = tmp.at(key);
这是我从 clang 12.0 获得的输出error: no matching member function for call to 'at'
auto result = tmp.at(key);
最佳答案
发生这样的事情需要三件事:
string_view
,即 C++17,所以这是一个有争议的问题)。at()
当容器具有透明比较器时,方法必须具有参与重载决议的重载。key_type
.在您的示例中,这些都不是真的。默认
std::less
比较器不是透明比较器,at()
没有这样的过载, 和 std::string
没有来自 std::string_view
的隐式转换.您无能为力
at()
, 但是你可以对比较器做一些事情 namely using the (transparent std::void
comparator) ,然后使用 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);
}
More complete demo
关于c++ std::map<std::string, int> 与std::string_view一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66342381/