首先利用抽象類linearlist來定義定義乙個線性表
template
<
class
t>
class
linearlist
;virtual
bool
empty()
const=0
;virtual
intsize()
const=0
;virtual t &
getelement
(int index)
const=0
;//返回index下標處元素
virtual
intelementpos
(const t &element)
const=0
;//返回element第一次出現位置
virtual
void
earse
(int index)=0
;//刪除index下標處元素
virtual
void
insert
(int index,
const t &element)=0
;//插入element至index下標處
virtual
void
ouput
(ostream &out)
const=0
;//輸出流物件
};
為了方便起見自定義乙個異常類用來在必要時丟擲下標越界異常
class
illegalindexvalue
private
: string message;
};
接下來就是自定義的乙個陣列類arraylist,繼承自linearlist,在實現虛函式的基礎上增加必要功能。
template
<
class
t>
class
arraylist
:public linearlist
;
首先是對建構函式,複製建構函式和析構函式的函式實現。建構函式中,在檢驗資料和理性的基礎上進行動態分配。而在複製建構函式中,先需要進行深拷貝賦值。在析構函式中對動態分配的記憶體進行釋放。
template
<
class
t>
arraylist
::arraylist
(int x)
arraylength = x;
listsize =0;
element =
new t[arraylength];}
template
<
class
t>
arraylist
::arraylist
(const arraylist &p)
template
<
class
t>
arraylist::~
arraylist()
在一維陣列中,我們常常會需要改變陣列長度,這時需要先構建乙個新陣列,再利用copy函式複製元素,最後釋放舊的陣列記憶體。
template
<
class
t>
void arraylist
::changelength
(int oldl,
int newl)
接下來就是兩個關鍵函式earse()和insert(),earse()思路是若刪除索引為index的元素,則將index+1,index+2,…,listsize-1的元素向左移動乙個位置,並釋放最後乙個元素。insert()思路是先檢驗陣列長度是否滿足需求。再利用copy_backward()將索引為index到listsize-1處元素右移,再插入索引為index的元素。
template
<
class
t>
void arraylist
::earse
(int index)
template
<
class
t>
void arraylist
::insert
(int index,
const t &element)
copy_backward
(element + index, element + listsize, element + listsize +1)
;//第三個引數是目的序列的結束迭代器
element[index]
= element;
}
最後則是其他函式的編寫,便不再做解釋,直接上**。
template
<
class
t>
void arraylist
::checkindex
(int index)
const
}template
<
class
t>
bool arraylist
::empty()
const
template
<
class
t>
int arraylist
::size()
const
template
<
class
t>
t &arraylist
::getelement
(int index)
template
<
class
t>
int arraylist
::elementpos
(const t &element)
template
<
class
t>
int arraylist
::getcapacity()
const
template
<
class
t>
void arraylist
::ouput
(ostream &out)
const
template
<
class
t>
ostream &
operator
<<
(ostream &out,
const arraylist
&x)
資料結構 自定義線性陣列
package com.accp.list 介面 author administrator param public inte ce mylist package com.accp.list 實現list的增 刪 改 查操作 author administrator param public cla...
資料結構 線性表之陣列
什麼叫陣列 陣列 array 是一種線性表資料結構。它是一組連續的記憶體空間,來儲存一組具有相同型別的資料。什麼線性表跟非線性表 線性表 通俗一點就是資料像一條線一樣排成的結構,線性表上的資料只有前後兩個方向,另外像鍊錶,佇列,棧等也是線性表的資料結構。非線性表 像二叉樹,圖,堆等,資料之間不只是前...
資料結構之線性表 C 陣列描述
前面我寫了幾節二叉樹,現在想想還是回過頭來吧線性表寫了 c 裡提供了強大的stl 標準模板庫 而且很多大神和相關書籍多提倡我們使用stl,切勿盲目自己寫,這樣反而效率更低。但是在使用stl的同時,能夠了解如何實現簡單的stl是很爽的。c 程式常用的資料描述方式是陣列描述和鏈式描述,而線性表可以用來說...