为什么具有 list<struct type>::itrator 的 struct 不能通过 clear() 删除?

Why struct which have list<struct type>::iterator can't delete by clear()?

本文关键字:struct clear 删除 不能 lt type gt itrator 为什么 list      更新时间:2023-10-16

我是iOS开发人员,我不熟悉C 。所以,我不明白为什么ImageMap的内容无法通过clear((方法删除?

struct ImageNode
{
  string key;
  UIImage *image;(UIImage is a class in Objective-C)
};
struct ImagePointer
{
  list<ImageNode *>::iterator it;
  bool isLRUQueue;
};
list<ImageNode *> FIFOQueue;
list<ImageNode *> LRUQueue;
map<string, ImagePointer *> imageMap;
//clear method
- (void)clear
{
  //why need for loop???
  for (auto it = imageMap.begin(); it != imageMap.end(); it++)
  {
    delete *it->second->it;
    delete it->second;
  }
  FIFOQueue.clear();
  LRUQueue.clear();
  imageMap.clear();
}

我不明白为什么ImageMap的内容不能被Clear((

删除

考虑,即使您确实将指针存储在列表中,也不意味着当您从列表中删除这些指针时,您要删除这些指针:

std::list<int*> l;
int i;
l.push_back(&i);
l.clear; // if list deleted the pointer contained within the list
         // then bad things would happen

std::list无法阅读您的思想,也不知道您是否要删除指针。必须在需要删除时删除指针。清晰只能从列表中删除元素。