簡體   English   中英

C ++ unordered_map迭代器在刪除元素后停止

[英]c++ unordered_map iterator stop after erasing element within

我正在嘗試制作一個函數,用存儲在哈希圖中的多項式來計算多項式導數,但是我不確定為什么在通過迭代擦除元素時迭代器會停止。 代碼如下,如果map.erase(i.first);迭代器將停止map.erase(i.first); 到位

哈希鍵包含指數度,存儲桶包含關聯系數。 輸入多項式為3x ^ 6 + 4x ^ 4 + 6x ^ 2 + 2

#include <iostream>
#include <unordered_map>
using namespace std;

unordered_map <int,int> derivative (unordered_map<int, int>& map) {
unordered_map <int, int> answer;
    map.erase(0);   // drop the constant in the polynomial

    for (auto i: map) {
        answer [i.first-1] = i.first * i.second;    //take the derivative
       // map.erase(i.first);     // erase the element after taking the derivative

    }
    return answer;
}

int main() {
    unordered_map <int,int> map = {{6,3},{4,4},{2,6},{0,2}};

    unordered_map<int,int> result = derivative(map);

    for (auto i: result)
        cout << i.second << "X^" << i.first << endl;

    return 0;
}

在使用范圍循環進行迭代時,無法從std::mapstd::unordered_map擦除當前元素,請改用迭代器:

for( auto it = map.begin(); it != map.end(); ) {
     if( condition ) map.erase( it++ );
     else ++it;
}

在您的特定情況下,可以簡化為:

for (auto it = map.begin(); it != map.end; ) {
    answer[it->first-1] = it->first * it->second;    //take the derivative
    map.erase(it++);
}

下列

for(auto i : map) {
    answer[i.first - 1] = i.first * i.second;    //take the derivative
    map.erase(i.first);     // erase the element after taking the derivative
}

遍歷元素。 如果使用map.erase(i.first); 擦除其中一個元素map.erase(i.first); 在迭代時,您將獲得未定義的行為。

如果您使用的是兼容c ++ 14的編譯器,則可以顯式使用迭代器,並使用erase的返回值對其進行更新。 這樣, 可以在遍歷容器時擦除元素。

因此,您可以執行以下操作:

for (auto it = map.begin(); it != map.end; ) {
    answer[it->first-1] = it->first * it->second;    //take the derivative
    it = map.erase(it);
}

暫無
暫無

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

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