交换方法的问题

Trouble with swap method

本文关键字:问题 方法 交换      更新时间:2023-10-16

我有一个问题与交换方法我试图写。我确信是这段代码,因为如果这些行没有注释,它只会在程序终止时抛出异常。将它们注释掉,文件就会正确结束。下面是我遇到问题的类和函数。

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_;
};

和包含swap的sort函数:

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,当程序终止时,它抛出了相同的"触发了一个断点"错误。同样,如果我注释掉问题行,错误就会消失。任何帮助将不胜感激!

通过检查代码,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]不存在。