c++ - unordered_set 与 boost 和 standard 的区别

标签 c++ boost unordered-set

我正在尝试将 boost 和 standard 中的 unordered_set 用于应用程序,目的是找到位置,即该集合中某些元素的索引。结果之间存在细微差别。 boost中的元素按照这个简单的程序进行了反转。问题出在哪里?

简单的“假设”代码:

#include <iostream>
#include <iterator>
#include <unordered_set>
#include <boost/unordered_set.hpp>

//using boost::unordered_set;
using std::unordered_set;
using std::distance;

int main()
{
  unordered_set<int> Set;
  int sz = 10;
    for(int k=0;k<sz;k++)
        Set.insert(k);
  unordered_set<int>::iterator ind_searched = Set.find(8);
  unordered_set<int>::size_type indx = distance( Set.begin(),
                                                 ind_searched );
  std::cout << " Index of element is "
            << indx << std::endl;
  return 0;
}

通过 boost 我得到

Index of element is 1

使用标准的 unordered_set 我得到了

Index of element is 8

我都编译了

g++ sgi_stl_1.cc -I /home/utab/external_libraries/boost_1_48_0/ -std=c++0x

最佳答案

您不应该对 unordered_mapunordered_set、它们的 multi 对应物或等效物或 hash_set 的任何实现中的顺序做出任何假设hash_maps。将元素的存储位置考虑为完全实现定义的,并且容易随时间变化。排序不仅在 boostC++11 标准之间会有所不同,而且在不同的硬件平台和不同的 C++ 实现之间也会有所不同。任何依赖特定顺序的代码都是有缺陷的。所以,你回答你的问题

where is the problem?

问题仅在于假设某些数据在无序数据结构中排序。

关于c++ - unordered_set 与 boost 和 standard 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461471/

相关文章:

c++ - while(true) 与 for(;;)

c++ - 依赖于 VS2010 的静态编译库时的 undefined symbol

c++ - 获取模块大小

c++ - 使用 boost::adjacency_list 的自定义边属性迭代边

c++ - 错误 : cannot open file 'boost_atomic-vc120-mt-1_58.lib' boost libs on Qt Windows8

c++ - 在只有 const shared_ptr 的 unordered_set 中找到一个 shared_ptr?

c++ - 关于 & 和 |手术

c++ - Visual Studio 2015 : Can't find `char * * __cdecl __p__environ(void)`

c++ - std::unordered_set<Foo> 作为类 Foo 的成员

c++ - unordered_set 中可能有两个键,它们被认为是相等的?