+-
unordered_set如何确定c中的插入顺序?
我知道人们在不关心集合中元素的顺序时会使用unordered_set.但是,当我在 C++ Shell上运行示例程序时

#include <iostream>
#include <unordered_set>
#include <string>

int main()

{
std::unordered_set<std::string> inputSet;
inputSet.insert("Hello world");
inputSet.insert("Abcdef");
inputSet.insert("This is the test string...");

for(const auto &val : inputSet)
  std::cout << val.c_str() << std::endl;

return 0;}

它给了我

This is the test string...
Abcdef
Hello world

我尝试运行它3或4次,它仍然给我相同的输出,这意味着有一种方法unordered_set确定插入顺序.

有人可以解释unordered_set如何确定插入顺序?

对不起,如果之前有人询问过,我在网上搜索了一段时间,我找不到这个问题的具体答案.提前致谢.

最佳答案
没有特定的排序……它使用默认的std :: hash来散列字符串.无论哈希值是什么,它都会被转换为容器中适当的桶索引.

我们正在讨论的哈希值可以得到:

auto hello = std::hash<std::string>()("Hello world");
auto abcd = std::hash<std::string>()("Abcdef");
auto test = std::hash<std::string>()("This is the test string...");

对于特定的STL实现,这解决为:

Hello maps to: 14420674105493498572
abcd maps to: 10830572898531769673
test maps to: 13068738153895491918

在C++Shell上看到它

通常通过应用%运算符将该值转换为适当的存储区索引.同样,std :: unordered_set的迭代器不是强制要求顺序遍历所有桶(碰撞怎么样?).因此,您不应该依赖于在程序运行之间从迭代器中观察到的任何顺序.

从C 14开始,std :: hash<>明确允许在不同的程序运行之间产生不同的结果.至quote:

Hash functions are only required to produce the same result for the
same input within a single execution of a program; this allows salted
hashes that prevent collision DoS attacks.

点击查看更多相关文章

转载注明原文:unordered_set如何确定c中的插入顺序? - 乐贴网