我正在尝试创建一个函数来计算多项式导数,多项式存储在 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::map
或 std::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/