unordered_map vs vector + 少量元素的自定义散列
unordered_map vs vector + custom hashing for small number of elements
目前我有一个嵌套的哈希图。内部映射键的范围非常大,但外部映射键只有 10 个不同的可能字符串。
unordered_map<string, unordered_map<int, list<string>>> nestedHashMap;
我切换到
会更有效率吗
vector<unordered_map<int, list<string>>>
并拥有自己的哈希函数
static int hashFunc(string stringToBeHashed){
switch(stringToBeHashed){
case "example1":
return 0;
.
.
.
case "example10":
return 9;
default:
return -1;
}
}
在每次查找之前做我自己的散列?就 space 复杂性而言,由于 unordered_map 是一个基于节点的容器,我认为这种向量方法可以为我节省一些 unordered_map 所需的每个节点内存。此外,我假设内部散列映射将保证最快的检索,即使键是一个 int。键的范围很大,所以我不认为在这里使用矢量会提高性能。正确的?任何 comments/tips 将不胜感激。
这里内存不是问题。
The inner map key has a very large range
这正是 hashmap 在这里是正确选择的原因
but the outer map key has only 10 different possible strings
你在滥用散列图。
换成一棵树(std::map
)。
(是的,如果你想自己写一个查找函数,你可以选择std::vector
)
顺便说一句,当你只有 10 个元素时,你不应该关心 space 复杂性主题 :)
更新:
您的外部容器的用途基本上是存储 10 个元素。
这是一个很小的数字,所以理论上你可以选择任何东西
你想要的容器(数组、树、哈希表)。
所以你应该选择最合适的。
选项是:
std::map
: 代码最少,自动排序元素
std::vector
: 最好使用space,但你应该自己写一个查找函数
std::hashmap
:用大炮射麻雀。您不需要它提供的 99% 的功能。这个容器的用途与你的不同
如果有人想知道,请使用
进行快速代码分析
vector<unordered_map<int, list<string>>
map<string, unordered_map<int, list<string>>
unordered_map<string, vector<unordered_map<int, list<string>>
vector 的平均时间最快,其次是 unordered_map,然后是 map。
目前我有一个嵌套的哈希图。内部映射键的范围非常大,但外部映射键只有 10 个不同的可能字符串。
unordered_map<string, unordered_map<int, list<string>>> nestedHashMap;
我切换到
会更有效率吗vector<unordered_map<int, list<string>>>
并拥有自己的哈希函数
static int hashFunc(string stringToBeHashed){
switch(stringToBeHashed){
case "example1":
return 0;
.
.
.
case "example10":
return 9;
default:
return -1;
}
}
在每次查找之前做我自己的散列?就 space 复杂性而言,由于 unordered_map 是一个基于节点的容器,我认为这种向量方法可以为我节省一些 unordered_map 所需的每个节点内存。此外,我假设内部散列映射将保证最快的检索,即使键是一个 int。键的范围很大,所以我不认为在这里使用矢量会提高性能。正确的?任何 comments/tips 将不胜感激。
这里内存不是问题。
The inner map key has a very large range
这正是 hashmap 在这里是正确选择的原因
but the outer map key has only 10 different possible strings
你在滥用散列图。
换成一棵树(std::map
)。
(是的,如果你想自己写一个查找函数,你可以选择std::vector
)
顺便说一句,当你只有 10 个元素时,你不应该关心 space 复杂性主题 :)
更新:
您的外部容器的用途基本上是存储 10 个元素。
这是一个很小的数字,所以理论上你可以选择任何东西
你想要的容器(数组、树、哈希表)。
所以你应该选择最合适的。
选项是:
std::map
: 代码最少,自动排序元素std::vector
: 最好使用space,但你应该自己写一个查找函数std::hashmap
:用大炮射麻雀。您不需要它提供的 99% 的功能。这个容器的用途与你的不同
如果有人想知道,请使用
进行快速代码分析vector<unordered_map<int, list<string>>
map<string, unordered_map<int, list<string>>
unordered_map<string, vector<unordered_map<int, list<string>>
vector 的平均时间最快,其次是 unordered_map,然后是 map。