数据结构(C语言版)严蔚敏算法(第二章)C++实现(书中的格式)

这篇博客主要讨论了一个C++程序员遇到的问题:在使用析构函数时程序触发了一个断点。作者通过代码展示了如何初始化和操作一个顺序列表,并在析构函数中遇到了问题。当析构函数被注释掉时,错误消失,这提示可能在释放内存资源时存在错误。博客中还包含了完整代码示例和主函数,用于演示问题所在和排序两个列表的合并操作。
摘要由CSDN通过智能技术生成

小白一枚,希望和大家共同学习进步,能够指出我的不足。
这里析构函数总是报错,说触发了一个断点,注释了析构函数就不报错了,老哥们知道怎么回事吗,

头文件。

#pragma once
#include<iostream>
using namespace std;
#define Maxsize 100
#define LISTINCREMENT 1000

class SqList {
protected:
	int* elem;
	int length;
	int listSize;
public:
	void init(int value[], int n) {
		this->listSize = n * 2;
		this->length = n;
		this->elem = new int[listSize];
		for (int i = 0; i < length; ++i) {
			this->elem[i] = value[i];
		}
	}
public:
	SqList(int list) {
		this->length = 0;
		this->listSize = list;
		this->elem = new int[listSize+10];
	}
	SqList(int value[], int n) {
		this->init(value, n);
	}
	~SqList();
	int GetElem(int i) {
		if (i<0 || i>this->length) {
			cout << "不合法。" << endl;
			return -1;
		}
		else {
			return elem[i - 1];
		}
	}
	int get_length() {
		return this->length;
	}
	void ListInsert(int i, int e) {
		if (i<0 || i>this->length+1) {
			cout << "要插入的位置有误。" << endl;
			exit(0);
		}
		else {
			int* p = this->elem;
			if (length >= listSize) {
				//长度不够进行扩容
				this->length += LISTINCREMENT;
				this->elem = new int[this->length];
				for (int j = 0; j < i; ++j) {
					this->elem[j] = p[j];
				}
				if (p != this->elem) {//释放原数组空间
					delete[] p;
				}
			}
			for (int j = this->length; j >= i; --j) {
				this->elem[j + 1] = p[j];
			}
			this->elem[i] = e;
			++this->length;
		}
	}
	void ListDelete(int i) {
		if (i<1 || i>this->length) {
			cout << "要删除的位置有误。" << endl;
		}
		else {
			for (int j = i - 1; j < this->length - 1; ++j) {
				this->elem[j] = this->elem[j + 1];
			}
		}
	}
	void printList() {
		for (int i = 0; i < this->length; ++i) {
			cout << this->elem[i] << " ";
		}
		cout << endl;
	}

};

SqList::~SqList() {
	//delete[] this->elem;
}
#include<iostream>
#include"shunxubiao.h"
using namespace std;

void MergeList(SqList La, SqList Lb, SqList& Lc) {
	int i = 1, j = 1,k=0;
	int al = La.get_length();
	int bl = Lb.get_length();
	while ((i <= al) && (j <= bl)) {
		if (La.GetElem(i) < Lb.GetElem(j)) {
			Lc.ListInsert(k, La.GetElem(i));
			++i;
			++k;
		}
		else {
			Lc.ListInsert(k, Lb.GetElem(j));
			++j;
			++k;
		}
	}
	while (i <= al) {
		Lc.ListInsert(k, La.GetElem(i));
		++i;
		++k;
	}
	while (j <= bl) {
		Lc.ListInsert(k, Lb.GetElem(j));
		++j;
		++k;
	}
}

int main() {
	int A[5] = { 2,3,6,7,9 };
	int B[7] = { 3,4,5,8,9,10,11 };

	SqList LA(A, 5);
	SqList LB(B, 7);
	SqList LC(15);
	MergeList(LA, LB, LC);
	LC.printList();
	LC.ListDelete(5);
	LC.printList();

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值