【c++】连续存储数组

#include <iostream>
using namespace std;
struct Array
{
	int* pBase;  //存储的是数组第一个元素的地址
	int len;	//数组所能容纳的最大元素个数
	int cnt; //当前数组的有效元素个数
};
void init(struct Array* pArr,int len);
bool append(struct Array* pArr,int val);
bool insert(struct Array* pArr,int pos,int val);
bool delete_arr(struct Array* pArr,int pos,int *pval);
bool isEmpty(struct Array* pArr);
bool isFull(struct Array* pArr);
void inversion(struct Array* pArr);
void show(struct Array* pArr);
int main() {
	struct Array arr;
	init(&arr, 6);
	append(&arr, 1);
	append(&arr, 2);
	append(&arr, 3);
	append(&arr, 4);
	append(&arr, 5);
	insert(&arr, 2, 9);
	int val;
	delete_arr(&arr, 2, &val);
	show(&arr);
	cout << val<<"\n";
	inversion(&arr);
	show(&arr);
	return 0;
}

void init(Array* pArr,int len)
{
	
	pArr->pBase = new int[len];
	if (NULL == pArr->pBase) {
		cout << "动态内存分配失败!\n";
		exit(-1);
	}
	else
	{
		pArr->len = len;
		pArr->cnt = 0;
	}
	return;
}

bool append(Array* pArr,int val)
{	if(isFull(pArr))
		return false;
	else
	{
	*(pArr->pBase + pArr->cnt) = val;
	pArr->cnt++;
	return true;
	}
}

bool insert(Array* pArr, int pos, int val)
{
	int cnt = pArr->cnt;
	if (pos > cnt-1 || pos < 0 || isFull(pArr)){
		return false;
	}
	for (int i = cnt;i > pos;i--) {
		*(pArr->pBase + i) = *(pArr->pBase + i - 1);
	}
	*(pArr->pBase + pos) = val;
	pArr->cnt++;
	return true;
	
}

bool delete_arr(Array* pArr, int pos, int* pval)
{	if(isEmpty(pArr) || pos < 0 || pos >= pArr->cnt)
		return false;
else {
	*pval = *(pArr->pBase + pos);
	for (int i = pos;i < pArr->cnt;i++) {
		*(pArr->pBase + i) = *(pArr->pBase + i + 1);
	}
	pArr->cnt--;
	return true;
}
}

bool isEmpty(Array* pArr)
{
	if (pArr->cnt == 0) {
		return true;
}
	return false;
}

bool isFull(Array* pArr)
{
	if (pArr->len == pArr->cnt) {
		return true;
}
	return false;
}

void inversion(Array* pArr)
{
	int cnt = pArr->cnt;
	int temp;
	for (int i = 0;i < cnt / 2;i++) {
		temp = *(pArr->pBase + i);
		*(pArr->pBase + i) = *(pArr->pBase + cnt - i - 1);
		*(pArr->pBase + cnt - i - 1) = temp;
	}
}

void show(Array* pArr)
{
	if (isEmpty(pArr)) {
		cout << "数组为空\n";
	}
	else
	{
		for (int i = 0;i < pArr->cnt;i++) {
			cout << *(pArr->pBase + i) << " ";
		}
		cout << "\n";

	}
}

看郝斌老师的课,就很舒服。
而且突然就对类有着更加深刻的理解,上面所有函数都作用于同一个结构体,如果用类写的话,会节省很多代码。提高代码的复用性。


版权声明:本文为weixin_48180029原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。