c++ unordered_map迭代器在删除元素后停止

标签 c++ hashmap unordered-map

我正在尝试创建一个函数来计算多项式导数,多项式存储在 HashMap 中,但我不确定为什么迭代器在我通过迭代删除元素时停止。代码如下,如果 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++);
}

关于c++ unordered_map迭代器在删除元素后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41049634/

相关文章:

java - 如何获取存储在 HashMap 中的列表中的对象,以创建新列表

c++ - C2338 : The C++ Standard doesn't provide a hash for this type with string and unique_ptr

c++ - 使用以数组为键的 unordered_map

c++ - AIR native 扩展 "The extension context does not have a method with the name"

C++ 结构体与类在内存方面的比较

c++ - 不知道为什么我会出现堆栈溢出

c++ - 寻找插入 vector 的最佳位置

java - 排序 HashMap

Java HashMap 和底层 values() 集合

c++ - 为什么 std::unordered_map 不能与 const std::string 键一起使用?