要使用std::string的std::hash特化而不构造字符串对象,你可以使用std::hashstd::string_view来代替。std::string_view是C++17中引入的一种轻量级字符串视图,它允许你在不拷贝字符串的情况下对其进行操作。
以下是一个示例代码:
#include
#include
#include
#include
int main() {
std::unordered_map> myMap;
std::string str1 = "hello";
std::string str2 = "world";
myMap[str1] = 1;
myMap[str2] = 2;
std::string_view strView1(str1);
std::string_view strView2(str2);
std::cout << myMap[strView1] << std::endl; // 输出: 1
std::cout << myMap[strView2] << std::endl; // 输出: 2
return 0;
}
在上面的示例中,我们使用std::unordered_map作为容器,并使用std::string_view作为键类型。在构建unordered_map时,我们使用std::hashstd::string_view作为哈希函数的特化。
这样,我们可以通过传递std::string_view对象作为键来访问和操作unordered_map中的元素,而无需创建新的std::string对象。