我試圖寫一個交換方法的問題。我確信這是代碼的這一部分,因爲只有在這些行未註釋的情況下程序終止時它纔會引發異常。將它們註釋掉,文件正常結束。 我的課程和我遇到問題的功能如下。交換方法的問題
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,它在程序終止時拋出相同的「觸發斷點」錯誤。同樣,如果我註釋掉問題行,錯誤就會消失。任何幫助,將不勝感激!
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –