交换方法的问题
Trouble with swap method
我有一个问题与交换方法我试图写。我确信是这段代码,因为如果这些行没有注释,它只会在程序终止时抛出异常。将它们注释掉,文件就会正确结束。下面是我遇到问题的类和函数。
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]
不存在。
相关文章:
- 最小硬币更换问题(自上而下方法)
- 使用同一类中的方法重新分配字段时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- Protobuf中重复字段的问题.使用重复字段进行序列化/反序列化的更好方法是什么?
- 此动态编程问题的自上而下方法
- 此解决方案中生成更改的方法数量(自上而下)有什么问题?
- 使用模板方法为标头提供空 cpp 时出现问题
- 这种针对 N Queen 问题的回溯方法不正确吗?
- C++ push() 和 pop() 方法使用指针的动态 LinkedList 的问题
- CreateFileA方法出现问题
- 必须使用尾随返回类型的示例,因为无法用旧方法解决问题
- 双重检查创建单例问题的方法
- C++ 指针问题 - 通过方法更新指针
- C++隐式/显式模板方法专用化问题
- 迭代快速排序方法的分区算法问题
- 单独的类声明和方法定义文件问题
- 我通过迭代加法将二进制数转换为十进制并检查单个字符(请参阅代码)的方法有什么问题?
- 如何通过动态规划方法解决这个问题?
- C++ 03 类模板 这是转换构造函数还是转换运算符?以及如何声明解决此问题的方法
- 一个c++语法问题:方法的类