|
举个例子来说明吧
学习C语言数据结构的时候曾经学过顺序表,其定义和“插入”操作如下:
- #include <stdlib.h>
- #define LISTINITSIZE 100
- #define LISTINCREASEMENT 10
- typedef struct SqList{
- ElemType *elem;
- int length;
- int listsize;
- }SqList;
- void listInsert_sq(SqList &L, int i, ElemType e)
- {
- if (i < 1 || i > L.length + 1)
- {
- printf("Invalid index!");
- exit(1);
- }
- if (L.length > L.listsize)
- {
- ElemType* newbase;
- newbase = (ElemType*) realloc(L.elem, sizeof(ElemType) * (L.length + LISTINCREASEMENT));
- L.elem = newbase;
- L.listsize += LISTINCREASEMENT;
- }
- ElemType *p, *q;
- q = L.elem + i - 1;
- for (p = L.elem + L.length - 1; p >= q; p --) *(p + 1) = *p;
- *q = e;
- L.length ++;
- } // 在第i个位置插入元素
复制代码
在上例中,顺序表的最大长度可以动态地变化。如果添加元素的个数超过了最大长度,则调用realloc重新申请更大的内存。
现在我想将顺序表封装成C++里的类,定义如下
- #pragma once
- #include <string>
- using namespace std;
- const int INITLISTSIZE = 1000;
- class SqList
- {
- public:
- int length;
- private:
- string* data;
- int size;
- public:
- void initList();
- void append(string s, int i);
- };
复制代码
想请问如果initList中是用new申请的内存,有没有方法申请更大内存呢?类似realloc
谢谢!!!!!!
没有。如果一定要封装这样的接口你需要重新申请更大自由存储区,进行深拷贝。然后释放之前申请的自由存储区。
|
上一篇: html下一篇: 类内函数指针如何调用
|