2017-02-24 71 views
0
bool StudentList::remove(const char * studentName) 
{ 
    for (int i = 0; i < MAX_SIZE; i++) 
    { 
     if (this->students[i]->isEqualTo(studentName)) // Finds a name to remove 
     { 
      cout << "Remove: "; // Displays name wished to be removed 
      students[i]->print(); 
      // delete[] students[i]; - Crashes 
      // students[i] = NULL; - Replaces removed name with null, stops working. 
      // students[i]->~Student(); - Call deconstructor, Crashes. 
      return true; 
     } 
    } 
    return false; 
} 

我只想從數組中刪除單個元素,但當我刪除該元素時不斷崩潰。刪除動態分配的數組C++

學生[i]是一個指針數組,我需要刪除選定的元素

+4

可能重複的[刪除數組元素並移動其餘的](http://stackoverflow.com/questions/879603/remove-an-array-element-and-shift-the-remaining-ones) – MSD

+0

請參閱在[this]中提供的解決方案(http://stackoverflow.com/questions/9246165/how-to-remove-elements-from-dynamically-allocated-array)舊的SO問題。 –

+0

我們需要看到'StudentList :: students'(它是一個數組,一個指針,一個unique_ptrs矢量,還是什麼?)以及基類型的定義。我們還需要知道「停止工作」是什麼意思,並且*代碼崩潰時。如果我們沒有[mcve],這可能會關閉。 –

回答

0

看來你要刪除的學生的每個實例,如果你能找到studentname。

students似乎是指向指針的二維結構指針。即; **students。但是,您正在以錯誤的方式刪除它。當您首先需要刪除students[i]的實例時,請刪除學生的實例。

另外,由於您在刪除實例後調用析構函數students[i]->~Student();,它可能會再次崩潰,因爲您已分配student[i] = NULL。那麼它會是,NULL->~Student() - 它也會導致崩潰。

您需要刪除它在以下方式:

for (int i = 0; i < MAX_SIZE; i++) 
{ 
    if (this->students[i]->isEqualTo(studentName)) // Finds a name to remove 
    { 
     students[i]->~Student(); 

     delete students[i]; 

     students[i] = NULL; 
    } 
} 
delete[] students; 

students = NULL; 
+0

你不能調用析構函數。 –

+0

而且你不能只刪除一個學生。 –

+0

@GoverNator:你爲什麼不能刪除一個學生? 'this-> student'似乎是一個指針數組。我希望不得不刪除每個元素(除了我會讓它成爲智能指針的矢量,並讓圖書館爲我完成繁重工作)。 –

0

首先quetion,如果你真的需要刪除「學生」的對象。如果是的話,你可以像添加一些不好的代碼:

students[i] = nullptr; 

如果你的學生都存儲不僅在這個數組中,你可以使存儲負責其刪除。但是由於稍後使用空指針,兩種方式都不太好。瞭解如何使用集合,例如vector。你將能夠從數組中移除指針。