gpt4 book ai didi

c++ - unordered_map:查找一对 std::string 和一对 std::string_view

转载 作者:行者123 更新时间:2023-12-05 03:22:19 27 4
gpt4 key购买 nike

给定一个以一对字符串为键的 HashMap ,例如:

std::unordered_map<std::pair<String, String>, int> myMap;

如何使用一对 std::string_view 进行查找,例如:

std::string s = "I'm a string";
std::string s2 = "I'm also a string";

std::string_view sv(s);
std::string_view sv2(s2);
myMap.find(std::make_pair(sv, sv2));

我想我需要在某处定义我自己的比较器,但我不确定从哪里开始。

最佳答案

使用 C++20 的异构查找可以做到这一点(参见 unordered_map::find() 的文档)。为此,必须定义哈希仿函数和相等仿函数,例如:

struct hash {
template <typename T>
auto operator()(const std::pair<T, T>& pair) const {
return std::hash<T>{}(pair.first) ^ std::hash<T>{}(pair.second); // not to be used in production (combining hashes using XOR is bad practice)
}

using is_transparent = void; // required to make find() work with different type than key_type
};

struct equal {
template <typename A, typename B>
auto operator()(const std::pair<A, A>& a,
const std::pair<B, B>& b) const {
return a.first == b.first && a.second == b.second;
}

using is_transparent = void; // required to make find() work with different type than key_type
};

然后必须将 map 的类型更改为 std::unordered_map<std::pair<std::string, std::string>, int, hash, equal>为了使用定义的仿函数。

find()现在按预期工作:

using namespace std::literals;

std::unordered_map<std::pair<std::string, std::string>, int, hash, equal> map{};

map.insert({std::pair{"a"s, "b"s}, 42});

if (auto it = map.find(std::pair{"a"sv, "b"sv}); it != map.end())
std::cout << it->second << std::endl;

if (auto it = map.find(std::pair{"x"s, "y"s}); it != map.end())
std::cout << it->second << std::endl;

// prints 42

可以使用 here 进行实现

关于c++ - unordered_map:查找一对 std::string 和一对 std::string_view,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72730133/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com