-2

I have a List of object pointers, and I'm trying to delete an element with an iterator pointer and I keep getting build errors as I'm not sure what the proper way to go about this is. Here is some of the code in question. Also, here is my error in a pastebin.


    class PlaneManager{
    private:
      list * planes = new list;
      list::iterator * iter = new list::iterator;      
    public:
        void DeletePlane(const string& tailNumber);

Here is the function in question that throws errors.


void PlaneManager::DeletePlane(const string& tailNumber){
  if(PlaneExists(tailNumber)){ 
    for (iter = planes->begin(); iter != planes->end();++iter){
      if(iter.GetTailNumber() == tailNumber)
        planes->erase(iter);
    }
  }else
    cout << "Couldn\'t find that plane." << endl;
}

Thanks for any insight you can provide, as I'm still a little lost with pointers.

2 Answers2

0

If you're using list::erase you have to be aware that it will modify the list. Therefore the iterator may be invalid after the erase. However list::erase will return the next valid iterator. So I recommend changing your loop to

for (iter = planes->begin(); iter != planes->end();){
   if(iter.GetTailNumber() == tailNumber)
      iter = planes->erase(iter);
    else
      iter++;
}
sashang
  • 11,704
  • 6
  • 44
  • 58
0

Your code doesn't work because you are not dereferencing the pointer you allocate for the iterator, or deterrence the iterator itself either. Try this instead:

void PlaneManager::DeletePlane(const string& tailNumber){
    if(PlaneExists(tailNumber)){
        for (*iter = planes->begin(); *iter != planes->end();){
            if((*iter)->GetTailNumber() == tailNumber)
                *iter = planes->erase(*iter);
            else
                ++(*iter);
        }
    }
    else
        cout << "Couldn\'t find that plane." << endl;
}

But, why are you using new at all? You shouldn't be using new in this example. Use this instead:

class PlaneManager{
private:
    list planes;
public:
    void DeletePlane(const string& tailNumber);

void PlaneManager::DeletePlane(const string& tailNumber){
    if(PlaneExists(tailNumber)){
        for (list::iterator iter = planes.begin(); iter != planes.end();){
            if(iter->GetTailNumber() == tailNumber)
                iter = planes->erase(iter);
            else
                ++iter;
        }
    }
    else
        cout << "Couldn\'t find that plane." << endl;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770