使用c++實現一下常用的資料結構,參考書為《資料結構、演算法與應用-c++語言描述》。
此次**為順序表,為了保證通用性採用模板機制,演算法本身沒有什麼難度,畢竟是基礎演算法,但是長時間不用c++,一些高階特性和陷阱著實讓人難受。
此次**共分三個檔案:
1、sq_list.h :實現順序表的結構和基本操作。
2、excp.h :實現異常類,關於命名空間的問題,直接將異常類加入到std空間內。
3、sq.cpp :主函式,簡單測試,可稍加簡單修改,轉為互動式程式。
sq_list.h
//construct the sq_list with template
#ifndef _sqlist_
#define _sqlist_
#include #include "excp.h"
using namespace std;
templateclass sqlist
bool isempty() const
templatefriend ostream& operator<<(ostream& out, const sqlist& x);
int getlength() const
bool findelement(int k, t& x) const;//get the kth value in the var x
int searchelement(t& x) const;//return the index of the var x
sqlist& deleteelement(int k, t& x);//remove the kth element and return it by x
sqlist& insertelement(int k, const t& x);//insert x
t* getdata() const
private:
t *data;
int length;
int maxsize;
};templatesqlist::sqlist(int maxsizel)
templatebool sqlist::findelement(int k, t& x) const
templateint sqlist::searchelement(t& x) const
templateostream& operator<<(ostream& out, const sqlist& x)
};class fullmemery
};void my_new_handler()
new_handler old_handler = set_new_handler(my_new_handler);
#endif
excp.h
#ifndef _excp_
#define _excp_
#include using namespace std;
class outofbounds
};class fullmemery
};void my_new_handler()
new_handler old_handler = set_new_handler(my_new_handler);
#endif
問題總結:
1、在模板類中過載操作符,穩妥的一種方法就是像程式中這樣在外層模板中(類模板)對於友元過載函式聲名成另一模板,否則會提示basic_ostream找不到匹配函式什麼的,估計是編譯器在定義ostream的時候把所有可用的查了一遍,結果沒找到合適的。
2、對於異常,使用自定義的異常,方便定製。
3、良好的程式設計習慣,遵循最小許可權原則,對於公有函式要進行一定的限制。
4、寫**要小心,錯將#ifndef寫成#ifdef浪費了大量時間。
順序表的實現
順序表很簡單,表裡面有個陣列,陣列中實際元素的個數 長度 lengthsqlcurrent,還有就是初始大小變數。可以解決約瑟夫環問題。最核心的兩個方法 刪除和插入,這兩個過程要移動元素。核心 package com.ibm.jzy.seqlist public class sqlist imple...
順序表的實現
順序表的操作 time limit 1000ms memory limit 65536k description 建立乙個順序表,然後在已建好的順序表上實現順序表插入和刪除等基本操作。最後輸出最終結果。input 有多組測試資料,每組資料由三部分組成。第一部分包含兩個整數n n 1000 和m m ...
順序表的實現
用c語言實現順序表的一些基本操作 前插 後插 前刪 後刪 查詢等一些基本操作。seqlist.h ifndef seqlist h define seqlist h include include include include define max 100 typedef int datatype...