我在代码中大量使用异常,因此我更喜欢使用at()
而不是find()
来查找元素,但我刚刚发现at()
似乎不支持std::string_view
,例如:
#include <map>
#include <iostream>
std::map<std::string, int, std::less<>> map{
{"one", 1},
{"two", 2},
};
const char* c = "onetwothree";
int main() {
std::string_view s(&c[3], 3);
std::cout << map.find(s)->second << std::endl;
std::cout << map.at(s) << std::endl; // will not compile
}
那么我可以在()和std::string_view
一起使用吗? 或者换句话说,
at()
是否可以支持异构查找?
自C++14标准以来,find
函数具有模板化的重载,这些重载支持与键等价的值。
at
函数没有这样的重载。 传递到处的的值必须与键的类型相同(或隐式可转换为键的类型)。