C++ 如何避免list.erase调用析构函数
我试图在列表中返回一个值,然后将其从列表中删除,但不删除其内容。但是当我调用C++ 如何避免list.erase调用析构函数,c++,list,destructor,erase,C++,List,Destructor,Erase,我试图在列表中返回一个值,然后将其从列表中删除,但不删除其内容。但是当我调用list.erase时,这个函数调用项目的析构函数。因此,删除项目后temp的内容也会被销毁。如何保存temp的内容 Vertice *temp = NULL; //Remove da lista o vértice escolhido para iniciar a busca. for (list<Vertice>::iterator it = lista.begin(); it != lista.end
list.erase
时,这个函数调用项目的析构函数。因此,删除项目后temp
的内容也会被销毁。如何保存temp
的内容
Vertice *temp = NULL;
//Remove da lista o vértice escolhido para iniciar a busca.
for (list<Vertice>::iterator it = lista.begin(); it != lista.end(); it++) {
if (it->getId() == (v)) {
temp = &*it;
lista.erase(it);
break;
}
}
Vertice*temp=NULL;
//拆除公共汽车上的车辆。
for(list::iterator it=lista.begin();it!=lista.end();it++){
如果(it->getId()==(v)){
温度=&*它;
删除(它);
打破
}
}
在调用擦除之前,使用唯一\u ptr
列表和交换
方法将对象的所有权移动到另一个指针。您可以复制该值,而不是在擦除之前使用指向该值的指针
Vertice temp;
temp = *it;
您可以通过使用std::optional
来改进这一点,以避免首先构建一个空的Vertice
。顶点的单数是“顶点”。@Lightness在英语中是的,但在葡萄牙语中不是,葡萄牙语似乎是代码的主要语言。非常感谢!我没意识到!非常感谢。但首先我必须学习独特的\u ptr
来学习如何使用它。它太强大了。