c++ - 根据 hash_map 键类型更改宏以选择单独的定义
问题描述
我有一个有趣的问题来处理 STL 哈希映射。
在我的代码中考虑这一点:
HSH_table(char*, obj_a) hash_1;
char* a = "abc";
char* b = "abc";
我正在 .h 文件中的某处进行 HSH_table 的 typedef。
#define HSH_table(Key, Data) __gnu_cxx::hash_map(Key, Data)
__gnu_cxx::hash_map 的问题在于它不适用于 char*。如果两个 char* 相同(不是指针,它的值),那么它不应该插入同一个插槽。在这种情况下,a 和 b 都应该进入同一个槽,因为它们共享相同的值。那是对的吗?我看到默认行为是它在不同的插槽中插入两个指针,因为它们的指针不同。
我不想更改我的源代码,但我可以更改 .h 文件。如果我想在同一个插槽中插入,我们可能需要编写一个比较器函数。我希望比较器功能特定于一个键,即 char*。
像这样的东西:
#define HSH_table(Key, Data) \
if (key == <char*>) { \
__gnu_cxx::hash_map(Key, Data, Comparator) \
else \
__gnu_cxx::hash_map(Key, Data)
首先,可能吗?
如果是,那么我们应该写什么,以便将 char* 视为不同,而将其他所有内容视为不同。什么是正确的方式匹配 char* 这是一个宏参数。
解决方案
您可能会使用以下内容:
template <typename Key, typename Value> struct hash_map_alias
{
using type = std::unordered_map<Key, Value>;
};
// Provide special comparer for C-string
template <typename Value> struct hash_map_alias<const char*, Value>
{
using type = std::unordered_map<Key, Value, StringComparer>;
};
template <typename Value> struct hash_map_alias<char*, Value>
{
using type = std::unordered_map<Key, Value, StringComparer>;
};
// And now your MACRO
#define HSH_table(Key, Data) typename hash_map_alias<Key, Data>::type
推荐阅读
- javascript - 如果浏览器的搜索栏打开,如何检测 Escape 键?
- asp.net-mvc - IIS 不反映我的 ASP.NET MVC 视图更改
- regex - 正则表达式匹配 2 个其他字符串之间的 URL 字符串*然后*替换一些文本
- android - 隐藏式字幕在视频 webview Android 中不起作用
- amazon-web-services - API 网关处理程序中的客户端标识
- javascript - 无法在 iOS 上的 Safari 中将冻结的地图保存到 IndexedDB
- python - 如果日期在时间范围内,则合并数据框
- numpy - 用 numpy 计算二进制掩码 IOU 的最快方法
- itfoxtec-identity-saml2 - 我如何在 azure ad asp.net core (itfoxtec) 中设置多个租户的流程
- google-sheets - 谷歌表格查询聚合函数分组可变日期