1
我需要刪除和擦除矢量上的對象指針。 我看到這個問題Should we delete before or after erase for an pointer in the vector?但我刪除對象指針後無法擦除。無法刪除和擦除矢量上的對象指針
如何解決?在這裏我的代碼。
#include <iostream>
#include <vector>
using namespace std;
class Foo
{
public:
class bar
{
public:
Foo &_owner;
int _id;
bar(Foo &owner,int id) : _id(id), _owner(owner){}
void remove()
{
for(vector<bar*>::iterator it=_owner.vbar.begin();it<_owner.vbar.end();it++)
{
if((*it)->_id == _id)
{
//delete object pointer
delete * it;
//remove element
it = _owner.vbar.erase(it); // error on this line.
}
}
}
};
vector<bar*> vbar;
Foo()
{
// add 10 elements
for(int i=0;i<10;i++)
vbar.push_back(new bar(*this ,i));
// remove element at 3
vbar.at(3)->remove();
}
};
int main(int argc, char *argv[])
{
Foo foo;
return 0;
}
將帖子 我固定這通過從外部酒吧類中刪除對象的指針通過添加不再使用欄ID(在Foo類刪除) 對這樣Foo類矢量。
#include <iostream>
#include <vector>
using namespace std;
class Foo
{
public:
class bar
{
public:
Foo &_owner;
int _id;
bar(Foo &owner,int id) : _id(id), _owner(owner) {}
void remove()
{
_owner.removeId = _id;
_owner.removeHelper();
}
};
vector<bar*> vbar;
int removeId;
Foo()
{
removeId = -1;
// add 10 elements
for(int i=0; i<10; i++)
vbar.push_back(new bar(*this ,i));
// remove element at 3
vbar.at(3)->remove();
}
void removeHelper()
{
for(vector<bar*>::iterator it=vbar.begin(); it<vbar.end(); it++)
{
if((*it)->_id == removeId)
{
//delete object pointer
delete * it;
//remove element
it = vbar.erase(it);
break;
}
}
removeId = -1;
}
};
int main(int argc, char *argv[])
{
Foo foo;
return 0;
}
'std :: shared_ptr'是你的朋友。 –