2016-09-16 58 views
-2

我試圖寫一個交換方法的問題。我確信這是代碼的這一部分,因爲只有在這些行未註釋的情況下程序終止時它纔會引發異常。將它們註釋掉,文件正常結束。 我的課程和我遇到問題的功能如下。交換方法的問題

class WordOccurrence { 
public: 
    //Constructor 
    WordOccurrence(const std::string& word = "", int num = 0) { num_ = num; word_ = word; }; 

    //Member Functions 
    bool matchWord(const std::string &); // returns true if word matches stored 
    void increment(); // increments number of occurrences 

    //Accessors 
    std::string getWord() const; 
    int getNum() const; 

private: 
    std::string word_; 
    int num_; 
}; 

//Bag 
class WordList { 
    public: 
     //Big 3: 
     WordList(int size = 0) { size_ = size; wordArray_ = size>0 ? new  WordOccurrence[size] : nullptr;}; 
     ~WordList() { delete[] wordArray_; }; 
     WordList(const WordList& list); 

     //Assignment Overload 
     WordList& operator =(const WordList& source); 

     //Member Functions 
     void addWord(const std::string &word); 
     friend void swap(WordOccurrence& first, WordOccurrence& second); 

     // void swap(WordOccurrence& lhs, WordOccurrence& rhs); 
     void sortList(); 
     void printList(); 
    private: 
     WordOccurrence *wordArray_; // a dynamically allocated array of WordOccurrences 
          // may or may not be sorted 
     int size_; 
}; 

和含交換排序功能:

void WordList::sortList() { 
for (int i = 0; i < size_; ++i) { 
    for (int j = size_; j > i; --j) { 
     if (wordArray_[j].getNum() < wordArray_[j - 1].getNum()) { 
      WordOccurrence tmp(wordArray_[j].getWord(), wordArray_[j].getNum()); //problem is 
     // tmp = wordArray_[j];       // is 
      wordArray_[j] = wordArray_[j-1];    // in 
      wordArray_[j-1] = tmp;      // here 
      //swap(wordArray_[j], wordArray_[j - 1]); 
     } 
    } 
} 

}

我試圖初始化「TMP」到一個空對象以及但這並不有所作爲無論是。 我也試過std :: swap,它在程序終止時拋出相同的「觸發斷點」錯誤。同樣,如果我註釋掉問題行,錯誤就會消失。任何幫助,將不勝感激!

+2

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

回答

0

通過檢查代碼,size_成員指定動態分配的wordArray_的大小。

for (int j = size_; j > i; --j) { 
    if (wordArray_[j].getNum() < wordArray_[j - 1].getNum()) { 

這是要過去的數組的末尾流失,導致不確定的行爲,並可能崩潰。

j起始等於size_。由於size_wordArray_的實際尺寸,並且wordArray_包含編號爲0到size_-1的元素,因此在第一次迭代中不存在wordArray_[j]。這是你的錯誤。

+0

謝謝!我應該已經發現了這一點,但我確信這與造成問題的不同尺寸的物體有關。 – Cos