![](/img/trans.png)
[英]Why is the time complexity for insertion of a string into an unordered_map, constant on average?
[英]Why is my std::unordered_map access time not constant
我編寫了一些代碼,以2分量向量為鍵來測試我的無序地圖性能。
std::unordered_map<Vector2i, int> m;
for(int i = 0; i < 1000; ++i)
for(int j = 0; j < 1000; ++j)
m[Vector2i(i,j)] = i*j+27*j;
clock.restart();
auto found = m.find(Vector2i(0,5));
std::cout << clock.getElapsedTime().asMicroseconds() << std::endl;
上面代碼的輸出:56(微秒)當我在for循環中將1000替換為100時,輸出為2(微秒),時間不是應該保持不變嗎?
我的Vector2i的哈希函數:
namespace std
{
template<>
struct hash<Vector2i>
{
std::size_t operator()(const Vector2i& k) const
{
using std::size_t;
using std::hash;
using std::string;
return (hash<int>()(k.x)) ^ (hash<int>()(k.y) << 1);
}
};
}
編輯:我添加了此代碼來計數for循環后的沖突:
for (size_t bucket = 0; bucket != m.bucket_count(); ++bucket)
if (m.bucket_size(bucket) > 1)
++collisions;
使用100 * 100元素:碰撞= 256
1000 * 1000元素:碰撞= 2048
哈希表保證了固定的攤銷時間 。 如果哈希表平衡良好(即哈希函數良好),則大多數元素將平均分配。 但是,如果哈希函數不太好,則可能會發生很多沖突,在這種情況下,訪問元素通常需要遍歷鏈接列表(在其中存儲發生沖突的元素)。 因此,請首先確保您的情況下的加載因子和哈希函數正常。 最后,確保您在發布模式下編譯了代碼,並且啟用了優化功能(例如,對於G ++ / clang ++,為-O3
)。
這個問題可能也很有用: 如何創建具有64位輸出的良好hash_combine(受boost :: hash_combine的啟發) 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.