C++ 释放错误后的堆使用
在Leetcode中出现自由错误后使用堆,似乎不了解根本原因。你们能帮我一下吗 大多数情况下,所有内容都在堆栈上声明。我唯一怀疑的是我在堆栈multiset temp上创建的浅层副本,但是你不能释放堆栈右侧没有在堆上创建的任何内容C++ 释放错误后的堆使用,c++,heap,C++,Heap,在Leetcode中出现自由错误后使用堆,似乎不了解根本原因。你们能帮我一下吗 大多数情况下,所有内容都在堆栈上声明。我唯一怀疑的是我在堆栈multiset temp上创建的浅层副本,但是你不能释放堆栈右侧没有在堆上创建的任何内容 class Solution { public: void earn_points(multiset<int> points,int currpoint, int& max){ set<int> unique
class Solution {
public:
void earn_points(multiset<int> points,int currpoint, int& max){
set<int> unique;
if(points.size() == 0){
cout <<"finalscore="<< currpoint << " "<<endl;
if(currpoint > max){
max = currpoint;
}
}
multiset<int> temp = points;
for(auto it=points.begin(); it != points.end(); ++it){
int num = *it;
if(unique.find(num) != unique.end()){
continue;
}
unique.insert(num);
int delete_num1 = num + 1;
int delete_num2 = num - 1;
points.erase(it);
if(points.find(delete_num1) != points.end())
points.erase(delete_num1);
if(points.find(delete_num2) != points.end())
points.erase(delete_num2);
cout << num <<" ";
for(auto i : points){
cout << i <<" ";
}
cout << endl;
earn_points(points,currpoint + num,max);
points = temp;
}
}
int deleteAndEarn(vector<int>& nums) {
multiset<int> points(nums.begin(),nums.end());
int max = INT32_MIN;
earn_points(points,0,max);
return max;
}
};
类解决方案{
公众:
无效赢取点数(多集点数、整数当前点数、整数和最大值){
设置唯一性;
如果(points.size()==0){
cout您的问题很可能是:
points.erase(it);
if(points.find(delete_num1) != points.end())
points.erase(delete_num1);
if(points.find(delete_num2) != points.end())
points.erase(delete_num2);
当您从多集删除内容时,它会使迭代器无效,因此,当您点击迭代器引用您在for…循环中删除的内容时,您引用的是不再存在的内容。由于您没有进行手动内存管理,请通读您正在使用的容器的,并确保您没有意外使用违反了其中一条规则。这里有一个你可以用来帮助解决问题的未遂副本:我想你可能想要点。擦除(它);
成为it=points.erase(它);
。一些需要阅读的文档:需要的不仅仅是it=points.erase(它)
如果通过erase
推进迭代器,则不希望使用for
中的++it
再次推进迭代器。正确,但无法指出被擦除的迭代器被重用的位置。最明显的重用是++it
for
的迭代表达式中的++code>。我没有看过那些代码所以可能还有更多。