在下面的代码中,hash_map自动排序或者按排序顺序插入元素.任何想法为什么这样做?建议请?? 这不是一个家庭作业问题,试图解决在glassdoor dot com上发布的面试问题.
#include <iostream>
#include <vector>
#include <ext/hash_map>
#include <map>
#include <string.h>
#include <sstream>
using namespace __gnu_cxx;
using namespace std;
struct eqstr
{
bool operator()(int i, int j) const
{
return i==j;
}
};
typedef hash_map<int, int, hash<int>, eqstr> myHash;
int main()
{
myHash array;
int inputArr[20] = {1,43,4,5,6,17,12,163,15,16,7,18,19,20,122,124,125,126,128,100};
for(int i=0;i<20;i++){
array[inputArr[i]] = inputArr[i]; //save value
}
myHash::iterator it = array.begin();
int data;
for (; it != array.end(); ++it) {
data = it->first;
cout << ":: " << data;
}
}
//!Output ::: 1:: 4:: 5:: 6:: 7:: 12:: 15:: 16:: 17:: 18:: 19:: 20:: 43:: 100:: 122:: 124:: 125:: 126:: 128:: 163
Run Code Online (Sandbox Code Playgroud)
哈希映射不会自动对数据进行排序.实际上,订单是未指定的,具体取决于您的哈希函数和输入顺序.只是在你的情况下,数字结果是排序的.
您可能希望阅读有关此容器如何存储数据的哈希表.
通过用999999999替换100可以创建一个清晰的计数器示例.结果是
:: 1:: 4:: 5:: 6:: 7:: 12:: 15:: 16:: 17:: 18:: 19:: 20:: 999999999:: 43:: 122:: 124:: 125:: 126:: 128:: 163
Run Code Online (Sandbox Code Playgroud)
(实际原因是hash_map bucket_count是193并且哈希函数int是一个身份函数,因此任何低于193的数字都会出现排序.)