簡體   English   中英

cpp 中的無序 map 行為

[英]unordered map behavior in cpp

我有這2個代碼,

代碼 1

#include<bits/stdc++.h>
using namespace std;

int main()
{
    unordered_map<int,int>m;

    int nums[]={1,1,3,4,5};

    for(auto x:nums)
    {
        m[x]++;
    }

    for(auto x:m)
    {
        cout<<x.first<<" "<<m[x.first]<<endl;
    }

return 0;

}

代碼 2

#include<bits/stdc++.h>
using namespace std;

int main()
{
    unordered_map<int,int>m;

    int nums[]={1,1,3,4,5}; int k=2;

    for(auto x:nums)
    {
        m[x]++;
    }

    for(auto x:m)
    {
        cout<<x.first<<" "<<m[x.first+k]<<endl;
    }

return 0;

}

第一個密碼的output是

5 1
4 1
1 2
3 1

但是第二個密碼的output是

5 0
4 0
5 0
7 0

我不明白為什么第二個代碼的 output 是這樣的,不應該是這樣的

5 0  //5 is the index and m[5+2]=0 hence 0
4 0  
1 1  //since m[1+2]=1 
3 1  

..................................................... ..................................................... ..................................................... ..................................................... .....................

當您執行m[x.first + k]時,當x.first + k不在m m 根據en.cppreference.com

如果發生插入並導致容器重新散列,則所有迭代器都將失效。 [...]

如果發生這種情況,您將在迭代 map 時使迭代器無效,因為for (auto x: m)只是使用迭代器進行迭代的一種隱藏方式。 因此,您的代碼具有未定義的行為(您正在使用無效的迭代器),因此您所看到的(以及為什么其他人可能會看到不同的東西)。

operator[],在 map 或 unordered_map 上,有可能改變容器,因為(正如你所依賴的)當你用一個不存在的鍵調用它時,它會立即添加一個默認構造的價值。 因此,在遍歷m時評估m[foo]是不安全的,除非您確定foo已經存在。

我不確定這段代碼試圖做什么,但假設它只是在移位鍵的值不存在時嘗試打印 0,您可以直接在該移位鍵上執行unordered_map::find並檢查是否返回迭代器有效,如果無效,則打印 0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM