我有一个集合,其中集合中的每个元素都是 shared_ptr
类型,我想从集合中删除一个元素,在 eclipse 中该元素实际上被删除了,但是当我使用 valgrind 在 bash 中测试它时,我得到了很多无效的大小错误......
所以这让我觉得也许有一种不同的方法来删除 shared_ptr
类型的元素?
PeoplePointer 中的每个元素都是某个人的类:
typedef std::shared_ptr<person> peoplePointer;
class AA {
std::set<peoplePointer> setOfPeople;
public:
// function getName() return name of the person (person is another class)
void removeSomeonefromA(const std::string& name) {
for (std::set<peoplePointer>::iterator it = setOfPeople.begin();it != setOfPeople.end(); it++) {
if(name == (*it).get()->getName()) {
setOfPeople.erase((it));
}
}
}
};
灵感来自 std::map 的等价物remove_if。
如果能够使用 C++11 或更高版本的编译器,则可以使用:
void removeSomeonefromA(const string& name)
{
for (set<peoplePointer>::iterator it = setOfPeople.begin(); it != setOfPeople.end(); /* Empty */ )
{
if(name == (*it).get()->getName())
{
it = setOfPeople.erase(it);
}
else
{
++it;
}
}
}
如果需要使用以前的编译器版本,可以使用:
void removeSomeonefromA(const string& name)
{
for (set<peoplePointer>::iterator it = setOfPeople.begin(); it != setOfPeople.end(); /* Empty */ )
{
if(name == (*it).get()->getName())
{
setOfPeople.erase(it++);
}
else
{
++it;
}
}
}