【问题】用C++结构体实现顺序表,数据超过数组长度后,表长自动+1

 1 #define LIST_INIT_SIZE 100
 2 #define LISTINCREMENT 10
 3 
 4 typedef int ElemType;
 5 
 6 typedef struct
 7 {
 8     //ElemType *elem;
 9     ElemType elem[LIST_INIT_SIZE];
10     int length;
11     int listsize;
12 }SqList;
13 
14 class _declspec(dllexport) Sq
15 {
16     public:
17         SqList sqList;
18 
19         Sq();
20         ElemType getElem(int i);
21         bool listInsert(int i, ElemType e);
22         bool listDelete(int i, ElemType &e);
23 };
sqlist.h
 1 #include <stdio.h>
 2 #include "stdlib.h"
 3 #include "sqlist.h"
 4 
 5 Sq::Sq()
 6 {
 7     //sq.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
 8 
 9     //if (!sq.elem) exit(0);
10 
11     this->sqList.length = 0;
12     this->sqList.listsize = LIST_INIT_SIZE;
13 }
14 
15 ElemType Sq::getElem(int i)
16 {
17     if (i<1 || i>sqList.length) return ElemType();
18 
19     ElemType elem = sqList.elem[i - 1];
20 
21     return elem;
22 }
23 
24 bool Sq::listInsert(int i, ElemType e)
25 {
26     if (i<1 || i>sqList.length + 1) return false;
27 
28     if (sqList.length >= sqList.listsize)
29     {
30         /*ElemType *newbase = (ElemType *)realloc(sq.elem, (sq.listsize + LISTINCREMENT) * sizeof(ElemType));
31         if (!newbase) exit(0);
32         sq.elem = newbase;
33         sq.listsize += LISTINCREMENT;*/
34         printf("hahaha");
35     }
36 
37     for (int j = sqList.length - 1; j >= i; j++)
38     {
39         sqList.elem[j + 1] = sqList.elem[j];
40     }
41 
42     sqList.elem[i - 1] = e;
43     ++sqList.length;
44     return true;
45 }
46 
47 bool Sq::listDelete(int i, ElemType &e)
48 {
49     if (i<1 || i>sqList.length - 1) return false;
50 
51     e = sqList.elem[i - 1];
52 
53     for (int j = i - 1; j < sqList.length; j++)
54     {
55         sqList.elem[j] = sqList.elem[j + 1];
56     }
57 
58     --sqList.length;
59 
60     return true;
61 }
sqlist.cpp
 1 #include <stdio.h>
 2 #include "sqlist.h"
 3 
 4 int main()
 5 {
 6     Sq sq;
 7     for (int i = 1; i <= 102; i++)
 8     {
 9         if (i == 100)
10         {
11             printf("%d", sq.sqList.length);
12         }
13         //当i==10时,sq.listInsert(int,int)方法中,插入之后length自动+1,执行自动操作后又自动+1。
14         sq.listInsert(i, i);
15     }
16     for (int i = sq.sqList.listsize; i <= sq.sqList.length; i++)
17     {
18         ElemType elem = sq.getElem(i);
19         printf("%d\n",elem);
20     }
21 
22     //ElemType e;
23     //listDelete(sq, 1,e);
24     //printf("%d\n", e);
25     //elem = getElem(sq, 1);
26     //printf("%d\n", elem);
27 
28     return 0;
29 }
main.cpp
当i==10时,sq.listInsert(int,int)方法中,插入之后length自动+1???执行自动操作后又自动+1。

猜你喜欢

转载自www.cnblogs.com/junlu/p/9494439.html