Chapter 14 Templates (樣板) Chapter 14 Templates (樣板)

Slides:



Advertisements
Similar presentations
1 生物計算期末作業 暨南大學資訊工程系 2003/05/13. 2 compare f1 f2  只比較兩個檔案 f1 與 f2 ,比完後將結果輸出。 compare directory  以兩兩比對的方式,比對一個目錄下所有檔案的相 似程度。  將相似度很高的檔案做成報表輸出,報表中至少要.
Advertisements

Divide-and-Conquer. 什麼是 divide-and-conquer ? Divide 就是把問題分割 Conquer 則是把答案結合起來.
6-1 指標簡介 6-2 指標與陣列 6-3 動態配置記憶體 6-4 本章綜合練習
布林代數的應用--- 全及項(最小項)和全或項(最大項)展開式
Introduction to Java Programming Lecture 13 Classes I OO Programming.
建立使用案例敘述 --Use Case Narrative
第七章 抽樣與抽樣分配 蒐集統計資料最常見的方式是抽查。這 牽涉到兩個問題: 抽出的樣本是否具有代表性?是否能反應出母體的特徵?
學習C++的基本語法 認識關鍵字與識別字的不同 學習程式碼偵錯的流程 學習如何提高程式的可讀性
: A-Sequence 星級 : ★★☆☆☆ 題組: Online-judge.uva.es PROBLEM SET Volume CIX 題號: Problem D : A-Sequence 解題者:薛祖淵 解題日期: 2006 年 2 月 21 日 題意:一開始先輸入一個.
“Rule” By OX. By Check CREATE TABLE 員工薪資 ( 編號 int IDENTITY PRIMARY KEY, 薪資 smallmoney, CHECK ( 薪資 > 0 AND 薪資
3Com Switch 4500 切VLAN教學.
Reference, primitive, call by XXX 必也正名乎 誌謝 : 部份文字取於前輩 TAHO 的文章.
What is static?. Static? 靜態 ? class Test { static int staticX; int instanceX; public Test(int var1, int var2) { this.staticX = var1; this.instanceX =
: OPENING DOORS ? 題組: Problem Set Archive with Online Judge 題號: 10606: OPENING DOORS 解題者:侯沛彣 解題日期: 2006 年 6 月 11 日 題意: - 某間學校有 N 個學生,每個學生都有自己的衣物櫃.
第一章 變數、常數及資料型態. 變數 C 程式語言的變數名稱 第一個字必須是英文字母或底線 (_) 之後可以是數字, 英文字母或底線 (_) 不可以是保留字 例: Num (Ο) _score (Ο) C&C (X) 8num (X)
: ShellSort ★★☆☆☆ 題組: Problem D 題號: 10152: ShellSort 解題者:林一帆 解題日期: 2006 年 4 月 10 日 題意:烏龜王國的烏龜總是一隻一隻疊在一起。唯一改變烏龜位置 的方法為:一隻烏龜爬出他原來的位置,然後往上爬到最上方。給 你一堆烏龜原來排列的順序,以及我們想要的烏龜的排列順序,你.
JAVA 程式設計與資料結構 第二章 JAVA 程式基本概念及操作. 第一個程式 /* * 這是第一個程式 (FirstP.java) */ class FirstP{ public static void main(String args[]){ System.out.println("Whatever.
: Problem E - Beverages ★★★☆☆ 題組: Contest Archive with Online Judge 題號: 11060: Problem E - Beverages 解題者:李重儀 解題日期: 2008 年 3 月 4 日 題意: Dilbert 大學剛畢業,他決定要和朋友出去。他有奇怪的嗜好,
STAT0_sampling Random Sampling  母體: Finite population & Infinity population  由一大小為 N 的有限母體中抽出一樣本數為 n 的樣 本,若每一樣本被抽出的機率是一樣的,這樣本稱 為隨機樣本 (random sample)
1. 假設以下的敘述為一未提供 “ 捷徑計算 ” 能力的程式段,試用程 式設計的技巧,使此敘述經此改 寫的動作後,具有與 “ 捷徑計算 ” 之 處理方法相同之處理模式。 if and then E1 else E2 endif.
例外處理. 內 容 大 綱 例外的產生 捕捉例外 丟出例外 例外的產生 (1/4) 一般常見的執行時期錯誤包括整數除法分母為 0(divide by zero) ,陣列索引值越限 (array index out of range) ,輸入輸出錯誤 (I/O error) 、檔案 不存在或無法存取.
MATLAB 程式設計 第 11 章 多維陣列 多維陣列的定義 在 MATLAB 的資料型態中,向量可視為 一維陣列,矩陣可視二維陣列,對於維 度 (Dimensions) 超過 1 的陣列則均可視 為「多維陣列」 (Multidimesional Arrays , 簡稱 N-D Arrays)
第 18 章 名稱空間與例外處理 18-1 名稱空間 18-1 名稱空間 18-2 例外處理 18-2 例外處理.
程式註解說明. 2 程式註解格式 塊狀註解 對檔案、 class 、 method 、資料結構、一段程式 …. 等程式區塊 做說明。 第一行的開頭必需為 “/*” 且沒有其他文字,最後一行的開頭 必需以 “*/” 做為結束,在中間每一行的開頭都必需是一個 “*” 。 單行註解 佔據一整行的說明。 以.
McGraw-Hill/Irwin © 2003 The McGraw-Hill Companies, Inc.,All Rights Reserved. 肆 資料分析與表達.
Monte Carlo Simulation Part.2 Metropolis Algorithm Dept. Phys. Tunghai Univ. Numerical Methods C. T. Shih.
JAVA 程式設計與資料結構 第十章 GUI Introdution III. File Chooser  File Chooser 是一個選擇檔案的圖形介面, 無論我們是要存檔還是要開啟檔案,使 用這個物件都會讓我們覺得容易且舒適。
第 7 章 程序與函數 7-1 模組化程式設計 7-1 模組化程式設計 7-2 VB.NET 的程序與函數 7-2 VB.NET 的程序與函數 7-3 程序與函數的變數範圍 7-3 程序與函數的變數範圍 7-4 VB.NET 常用的內建函數 7-4 VB.NET 常用的內建函數 7-5 遞迴函數 7-5.
Chapter 13 塑模靜態觀點:物件圖 Static View : Object Diagram.
Introduction to Java Programming Lecture 17 Abstract Classes & Interfaces.
24-6 設定開始與結束場景中的 程式 最後我們要替這個遊戲收個尾, 幫它把開始 的等待畫面跟結束畫面處理一下。
: The largest Clique ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11324: The largest Clique 解題者:李重儀 解題日期: 2008 年 11 月 24 日 題意: 簡單來說,給你一個 directed.
Matlab Assignment Due Assignment 兩個 matlab 程式 : Eigenface : Eigenvector 和 eigenvalue 的應用. Fractal : Affine transform( rotation, translation,
Chapter 20 塑模動態觀點:狀態圖 Statechart Diagram. 學習目標  說明狀態圖的目的  定義狀態圖的基本記號  展示狀態圖的建構  定義活動、內部事件及遞延事件的狀態 圖記號.
: Happy Number ★ ? 題組: Problem Set Archive with Online Judge 題號: 10591: Happy Number 解題者:陳瀅文 解題日期: 2006 年 6 月 6 日 題意:判斷一個正整數 N 是否為 Happy Number.
: Fast and Easy Data Compressor ★★☆☆☆ 題組: Problem Set Archive with Online Judge 題號: 10043: Fast and Easy Data Compressor 解題者:葉貫中 解題日期: 2007 年 3.
資料庫程式設計與系統管理 SQL Server 2005 Express 第六章 進階資料庫設計.
: Ahoy, Pirates! ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11402: Ahoy, Pirates! 解題者:李重儀 解題日期: 2008 年 8 月 26 日 題意:有一個海盜島有 N 個海盜,他們的編號 (id)
Fugacity Coefficient and Fugacity
: Multisets and Sequences ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 11023: Multisets and Sequences 解題者:葉貫中 解題日期: 2007 年 4 月 24 日 題意:在這個題目中,我們要定義.
:Nuts for nuts..Nuts for nuts.. ★★★★☆ 題組: Problem Set Archive with Online Judge 題號: 10944:Nuts for nuts.. 解題者:楊家豪 解題日期: 2006 年 2 月 題意: 給定兩個正整數 x,y.
資料結構實習-一 參數傳遞.
6-2 認識元件庫與內建元件庫 Flash 的元件庫分兩種, 一種是每個動畫專 屬的元件庫 (Library) ;另一種則是內建元 件庫 (Common Libraries), 兩者皆可透過 『視窗』功能表來開啟, 以下即為您說明。
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2008.
4 堆疊與佇列 4.1 前言 四種基本的資料結構 (可儲存資料的容器) 陣列 (Array)、串列(List): 最基本
Section 4.2 Probability Models 機率模式. 由實驗看機率 實驗前先列出所有可能的實驗結果。 – 擲銅板:正面或反面。 – 擲骰子: 1~6 點。 – 擲骰子兩顆: (1,1),(1,2),(1,3),… 等 36 種。 決定每一個可能的實驗結果發生機率。 – 實驗後所有的實驗結果整理得到。
函式 Function Part.2 東海大學物理系‧資訊教育 施奇廷. 遞迴( Recursion ) 函式可以「呼叫自己」,這種動作稱為 「遞迴」 此程式的執行結果相當於陷入無窮迴圈, 無法停止(只能按 Ctrl-C ) 這給我們一個暗示:函式的遞迴呼叫可以 達到部分迴圈的效果.
JAVA 程式設計與資料結構 第二十章 Searching. Sequential Searching Sequential Searching 是最簡單的一種搜尋法,此演 算法可應用在 Array 或是 Linked List 此等資料結構。 Sequential Searching 的 worst-case.
資料結構實習-二.
演算法 8-1 最大數及最小數找法 8-2 排序 8-3 二元搜尋法.
845: Gas Station Numbers ★★★ 題組: Problem Set Archive with Online Judge 題號: 845: Gas Station Numbers. 解題者:張維珊 解題日期: 2006 年 2 月 題意: 將輸入的數字,經過重新排列組合或旋轉數字,得到比原先的數字大,
Structural Equation Modeling Chapter 6 CFA 根據每個因素有多重指標,以減少 測量誤差並可建立問卷的構念效度 驗證性因素分析.
第 17 章 樣板 17-1 樣板的基礎 17-1 樣板的基礎 17-2 樣板函數 17-2 樣板函數 17-3 樣板類別 17-3 樣板類別 17-4 非型態參數的樣板類別 17-4 非型態參數的樣板類別 17-5 樣板類別的繼承 17-5 樣板類別的繼承 17-6 特化樣板與靜態成員 17-6 特化樣板與靜態成員.
Learning Method in Multilingual Speech Recognition Author : Hui Lin, Li Deng, Jasha Droppo Professor: 陳嘉平 Reporter: 許峰閤.
Chapter 10 m-way 搜尋樹與B-Tree
: Function Overloading ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 11032:Function Overloading 解題者:許智祺 解題日期: 2007 年 5 月 8 日 題意:判對輸入之數字是否為.
演算法課程 (Algorithms) 國立聯合大學 資訊管理學系 陳士杰老師 Course 7 貪婪法則 Greedy Approach.
JAVA 程式設計與資料結構 第十六章 Hash Tables. Introduction Hash Tables 結構為一個 Array ,稱之為 Bucket array 。 如果想要新增一個物件,要根據這個物件的特性 將其加入 Hash Table 內。 Bucket Array 用 A 來代替,其.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2009.
Teacher : Ing-Jer Huang TA : Chien-Hung Chen 2015/6/30 Course Embedded Systems : Principles and Implementations Weekly Preview Question CH7.1~CH /12/26.
函式 Function 東海大學物理系‧資訊教育 施奇廷. 函式簡介 當程式越來越大、越複雜時,程式的維護、 除錯會變得更困難,此時必須引入函式來 簡化程式或將程式分段,將程式重複的部 分改寫為函式,將程式「模組化」 這種作法有下列優點:節省程式發展的時 間、邏輯容易瞭解、程式容易除錯、可分 工合作完成程式.
Visual C++重點複習.
1 Introduction to Java Programming Lecture 3 Mathematical Operators Spring 2008.
1 Introduction to Java Programming Lecture 2: Basics of Java Programming Spring 2010.
Microsoft Excel.
Introduction to Java Programming Lecture 16 Super and Sub Classes.
: Finding Paths in Grid ★★★★☆ 題組: Contest Archive with Online Judge 題號: 11486: Finding Paths in Grid 解題者:李重儀 解題日期: 2008 年 10 月 14 日 題意:給一個 7 個 column.
幼兒行為觀察與記錄 第八章 事件取樣法.
VHDL語法(3).
: How many 0's? ★★★☆☆ 題組: Problem Set Archive with Online Judge 題號: 11038: How many 0’s? 解題者:楊鵬宇 解題日期: 2007 年 5 月 15 日 題意:寫下題目給的 m 與 n(m
Presentation transcript:

Chapter 14 Templates (樣板) Chapter 14 Templates (樣板)

14.1 Introduction 是考慮以下程式問題: ◦ 請撰寫一個函式將一個整數陣列中的每個元素依序印出。 ◦ 如果現在我們也想把字元陣列、浮點數陣列、字 串陣列的元素印出的話,跟怎麼作?  必須另外為特定的型態來撰寫此型別專屬的副函式!  樣板( template )的作用即用來解決這樣的問題。 void printArray(const int a[], const int count) { for (int i=0; i<count; i++) cout << a[i] << “ “; cout << endl; }

14.1 Introduction Function templates and class templates ◦ Programmers are enable to specify an entire range of related functions and related classes  Function-template specializations and class-template specializations can be generated, respectively. ◦ Generic programming

Software Engineering Observation 14.1 Most C++ compilers require the complete definition of a template to appear in the client source-code file that uses the template. For this reason and for reusability, templates are often defined in header files, which are then #included into the appropriate client source-code files. ◦ For class templates, this means that the member functions are also defined in the header file.

14.2 Function Templates Function Templates ◦ Used to produce overloaded functions that perform identical operations on different types of data  First, programmer writes a single function-template definition.  Compiler generates separate object-code functions (function-template specializations) based on argument types in calls to the function template

14.2 Function Templates Function-template definitions ◦ Starting with a template header  Keyword template  List of template parameters  Enclosed in angle brackets ( )  Each template parameter is preceded by keyword class or keyword typename (both are interchangeable)  Used to specify types of arguments to, local variables in and return type of the function template  Examples  template

Common Programming Error 14.1 Not placing keyword class or keyword typename before each type template parameter of a function template is a syntax error.

fig14_01.cpp (1 of 2) Type template parameter T specified in template header 注意:樣板的定義由 template 開始,角刮號中一定至 少要定義一種型態或類別

fig14_01.cpp (2 of 2) Creates a function-template specialization of printArray where int replaces T Creates a function-template specialization of printArray where double replaces T Creates a function-template specialization of printArray where char replaces T

Common Programming Error 14.2 If a template is invoked with a user-defined type, and if that template uses operators (e.g., ==, +, <=) with objects of that class, those operators must be overloaded. Forgetting to overload such operators causes compilation errors.

Indicate Any Error #include using namespace std; class Test { public: Test(int s=0) { a = s; } private: int a; } template void printArray(const T *a, const int count) { for (int i=0; i<count; i++) cout << a[i] << endl; } void main () { Test b[4]; printArray(b, 4); } Error: How to fix?

Performance Tip 14.1 Remember that multiple function-template specializations are instantiated in a program (at compile time), despite the fact that the template is written only once. ◦ For the example of fig14_01.cpp, three specialized functions are generated and compiled: printArray(const int *, const int); printArray(const double *, const int); printArray(const char *, const int);

14.4 Class Templates Class templates (or parameterized types) ◦ Class-template definitions start with a header such as  template ◦ Additional type parameters can be specified using a comma-separated list. For example  template

14.4 Class Templates 使用類別樣板( class template )的時機: ◦ 樣板的寫法並非適用於實作所有的類別。  如果類別成員函式的運算大多與成員變數的存取有關,或 類別過於複雜,較不適合採用樣板來實作。  如果類別的功用主要作為一種資料結構,單純作為資料的 「容器」,則比較適合以樣板來實作。  例如,堆疊、佇列、鏈結串列等。 本節將以「堆疊」( Stack )來說明類別樣板 的實作語法。

An Introduction to Stack A kind of data structure Last-In-First-Out (LIFO) Push (A) Push (B) Push (C) Push (D) Push (E) Pop () Which one is popped by the function Pop()? A B C D E Add a new item on the top of stack. Get the item the item at the top of stack and remove it from the stack. top

Examples of Stack (0, 0) (0, 1) (1, 1) (1, 0) (2, 0) (2, 1) (3, 1) (3, 0) (4, 0) (4, 1) (3, 2)

An Implementation of Stack Implement Stack using an array. ◦ Assume integer elements are considered. class Stack { public: Stack (int = 10); //Default constructor ~Stack(); bool push (int); //Push an integer into the stack; return true if successful bool pop (int &); //Pop an integer from the stack; return true if successful bool isEmpty() const; //Return true if the array is empty bool isFull() const; //Return true if the array is full private: int size; //array size int top; //initialized to -1; always maintain the next index to pop int *stackPtr; };

Stack (int s) : size( (s > 0)? s : 10 ), top(-1) { stackPtr = new int[size]; } ~Stack() { delete [] stackPtr; } bool Stack::push (int pushValue) { if (!isFull()) { stackPtr[++top] = pushValue; return true; } return false; } bool Stack:: pop (int &popValue) { if (!isEmpty()) { popValue = stackPtr[top--]; return true; } return false; } bool Stack::isFull () const { return (top == size); } bool Stack::isEmpty () const { return (top == -1); }

An Implementation of Stack Now consider object elements. class Stack { public: Stack (int = 10); //Default constructor ~Stack(); bool push (const Point &); //Push a Point object into the stack; return true if successful bool pop (Point &); //Pop a Point object from the stack; return true if successful bool isEmpty() const; //Return true if the array is empty bool isFull() const; //Return true if the array is full private: int size; //array size int top; //initialized to -1; always maintain the next index to pop Point *stackPtr; }; class Point { public: Point(int a=0, int b=0) : x(a), y(b) { } private: int x, y; };

Stack (int s) : size( (s > 0)? s : 10 ), top(-1) { stackPtr = new Point[size]; } ~Stack() { delete [] stackPtr; } bool Stack::push (int pushValue) { if (!isFull()) { stackPtr[++top] = pushValue; return true; } return false; } bool pop (int &popValue) { if (!isEmpty()) { popValue = stackPtr[top--]; return true; } return false; } bool Stack::isFull () { return (top == size); } bool Stack::isEmpty () { return (top == -1); } 請注意,陣列中如果每個元素都 是物件,在呼叫每個物件的建構 子時不會給引數,因此請記得為 你的資料類別(如本例的 Point ) 提供預設建構子。 請注意此兩行敘述。 在這兩行中,涉及物件的指定。因為最 好為資料類別(如本例的 Point )提供拷 貝建構子與賦值運算子多載函式。 請注意此兩行敘述。 在這兩行中,涉及物件的指定。因為最 好為資料類別(如本例的 Point )提供拷 貝建構子與賦值運算子多載函式。

Observations Stack 的操作在於物件的建立與指定,其運作與資料 的內容無關。 ◦ Stack 不需要是 Point 類別的夥伴類別;因為 Stack 的運作沒有 讀取其成員變數的必要。 Stack 扮演「容器」的角色;代表其當中存放的內容 (型態)隨時會改變。 ◦ 內容一改變,就必須重新實作新的 Stack 類別?! ◦ 解決方法:利用樣板( template )

Stack.h (1 of 3) 這一行寫在類別的宣告前面,代表要產 生一個 class template (類別樣板),角 刮號中由 class 或 typename 接續一個標幟 名 T ,稱為參數型態;用來代表使用者 可自行定義的型態 在此類別樣板的成員宣告中,接著即以 型別參數 T 來指定其內容的型別。

Stack.h (2 of 3) 資料成員 stackPtr 是一個指標, 指向一個 T 的陣列 如果將成員函式提到類別宣告 外部來實作,則每個函式都在 跟在一個樣板標頭的後面。 注意!!在此, Stack 是被實作為一個 類別樣本,一般化樣板的類別名稱為 Stack ,而非

Stack.h (3 of 3)

Note ★ ★ ★ ★ ★ Software Engineering Observation 14.1 ◦ Most C++ compilers require the complete definition of a template to appear in the client source-code file that uses the template. ◦ For class templates, this means that the member functions are also defined in the header file. ◦ 請注意!樣板的運作模式是,是由編譯器根據樣板的定義,以及使 用者所指定的型別,先自動產生出對應的程式碼後再行編譯。編譯 的過程與一般的類別不同(個別編譯後進行連結),因此大部分的 C++ 編譯器會要求使用樣板的程式檔要包含完整的樣板定義,所以 我們會把樣板的完整定義(包含成員函式的實作)一律寫在.h 檔中 ,這和一般我們設計類別時,要求宣告和實作要分開的情況不同。

fig14_03.cpp (1 of 3) 樣板類別定義的所有內容在此 標頭檔中 產生特殊化樣板類別( class- template specialization ), Stack 。 編譯器會將型態 double 與參數型 態 T 連結

fig14_03.cpp (2 of 3) 產生特殊化樣板類別( class- template specialization ), Stack 。 編譯器會將型態 int 與參數型態 T 連結

fig14_03.cpp (3 of 3) 註:在本例中,編譯器實際上將套用型別參數,分別產生兩個 Stack 的 副本用來處理 double 與 int 的元素資料,就效能來看,其和使用者自己 把 Stack 重寫兩次的結果是一樣的。不過,使用樣板的好處主要是在增 加程式碼的可再利用率,避免程式碼的重複撰寫。

fig14_04.cpp (1 of 3) 在本例中,主要示範如何建立一個函式樣 板,並以 Stack 的物件作為其參數 代表使用參數型態 T ,用來代 表 Stack 中的儲存資料型別 注意「 += 」運算子的使用;如果 T 是一個自訂類 別的話,則如果要在其物件進行「 += 」的運算, 代表此類別必須要 _______________________

fig14_04.cpp (2 of 3)

14.5 Nontype Parameters and Default Types for Class Templates Nontype template parameters ◦ Can have default arguments ◦ Are treated as const ◦ Example  Template header: template  In the constructor, we can use nontype paramemter stackPtr = new T[ elements ];  Declaration: Stack salesFigures;

14.5 Nontype Parameters and Default Types for Class Templates Type parameters can have default arguments too ◦ Example  Template header: template Declaration: Stack<> jobDescriptions;

Exercise Use the concept of template to implement Queue. What is a queue? ◦ First-In-First-Out (FIFO) Push (A) Push (B) Push (C) Push (D) Pop (E) Pop () Which one is deleted by the function Pop()? A B C D E Add a new item on the rear of queue. Get the item at the front of queue and remove it from the queue. rearfront

An Implementation of Queue Assume integer elements are considered. class Queue { public: Queue (int = 10); //Default constructor ~ Queue(); bool push (int); //Push an integer into the queue; return true if successful bool pop (int &); //Pop an integer from the queue; return true if successful bool isEmpty() const; //Return true if the array is empty bool isFull() const; //Return true if the array is full private: int size; //array size int front, rear; //initialized to 0 int *queuePtr; };

Implementing Queue Using Array Suppose the length of array is n. ◦ This approach runs into a problem when rear equals to n- 1. ◦ Shifting all elements to the left? Time-consuming. AABABC rear BC front BCD rearfront

Circular Queue A BC D ABCD rear front rear front Push (A) Push (B) Push (C) Push (D) Pop () Push (E) Push (F) Push (G) Push (H) Push (I) rear front E FG H I E rear F G HI

front rear A BC D E FG H How do know whether the queue is empty or full?

An Implementation of Queue Assume integer elements are considered. class Queue { public: Queue (int = 10); //Default constructor ~ Queue(); bool push (int); //Push an integer into the queue; return true if successful bool pop (int &); //Pop an integer from the queue; return true if successful bool isEmpty() const; //Return true if the array is empty bool isFull() const; //Return true if the array is full private: int size; //array size int front, rear; //initialized to -1; always maintain the next index to pop int *queuePtr; }; Queue (int s) : size( (s > 0)? s : 10 ), front(0), rear(0) { queuePtr = new int[size]; } ~Queue() { delete [] queuePtr; } bool Queue::push (int pushValue) { if (!isFull()) { rear = (rear+1) % size; queuePtr[rear] = pushValue; return true; } return false; } bool Queue:: pop (int &popValue) { if (!isEmpty()) { front = (front+1) % size; popValue = queuePtr[front]; return true; } return false; } bool Queue ::isFull () const { return ((rear+1) % size == front); } bool Queue ::isEmpty () const { return (rear == front); }

Implementing Queue Using Template #ifndef QUEUE_H #define QUEUE_H template class Queue { public: Queue(int = 10); ~Queue(); bool push( const T & ); bool pop( T & ); bool isFull() const; bool isEmpty() const; private: int size; int front, rear; T *queuePtr; } ;

Implementing Queue Using Template Assume integer elements are considered. class Queue { public: Queue (int = 10); //Default constructor ~ Queue(); bool push (int); //Push an integer into the queue; return true if successful bool pop (int &); //Pop an integer from the queue; return true if successful bool isEmpty() const; //Return true if the array is empty bool isFull() const; //Return true if the array is full private: int size; //array size int front, rear; //initialized to -1; always maintain the next index to pop int *queuePtr; }; template Queue :: Queue (int s) : size( (s > 0)? s : 10 ), front(0), rear(0) { queuePtr = new T[size]; } template Queue :: ~Queue() { delete [] queuePtr; } template bool Queue:: push ( const T &pushValue ) { if (!isFull()) { rear = (rear+1) % size; queuePtr[rear] = pushValue; return true; } return false; }

Implementing Queue Using Template class Queue { public: Queue (int = 10); //Default constructor ~ Queue(); bool push (int); //Push an integer into the queue; return true if successful bool pop (int &); //Pop an integer from the queue; return true if successful bool isEmpty() const; //Return true if the array is empty bool isFull() const; //Return true if the array is full private: int size; //array size int front, rear; //initialized to -1; always maintain the next index to pop int *queuePtr; }; template bool Queue :: pop ( T &popValue ) { if (!isEmpty()) { front = (front+1) % size; popValue = queuePtr[front]; return true; } return false; } template bool Queue :: isFull () const { return ((rear+1) % size == front); } template bool Queue :: isEmpty () const { return (rear == front); } #endif

7.11 Introduction to C++ Standard Library Class Template vector C-style pointer-based arrays ◦ Have great potential for errors and several shortcomings  C++ does not check whether subscripts fall outside the range of the array  Two arrays cannot be meaningfully compared with equality or relational operators  One array cannot be assigned to another using the assignment operators

7.11 Introduction to C++ Standard Library Class Template vector Class template vector ◦ Available to anyone building applications with C++ ◦ Can be defined to store any data type  Specified between angle brackets in vector  All elements in a vector are set to 0 by default ◦ Member function size obtains size of array  Number of elements as a value of type size_t ◦ vector objects can be compared using equality and relational operators. ◦ Assignment operator can be used for assigning vector s. ◦ Individual elements can be accessed with square brackets.

7.11 Introduction to C++ Standard Library Class Template vector vector member function at ◦ Provides access to individual elements ◦ Performs bounds checking  Throws an exception when specified index is invalid  Accessing with square brackets does not perform bounds checking

fig07_26.cpp (1 of 6) 類別樣板 vector 將儲 存 int 元素 vector 為特殊化類別樣板, 儲存資料型別已經明確定義 vector 類別樣板內含成員 變數 size ,用來記錄當中 的元素個數 注意!使用 vector 類別樣 板前必須引入 標 頭檔

fig07_26.cpp (2 of 6) 你可以比較兩個 vector 物件是否相等。 因為該類別 _______ 了「 != 」運算子 你也可以從一個 vector 物件建立它的副 本,或作兩個物件的指定。因為該類別 提供了 _______ 以及 _________

fig07_26.cpp (3 of 6) vector 多載註標運算子,用來存取某一 個元素的內容;然而註標運算子的多載 函式並未提供範圍的檢查 函式 at() 也同樣可以用來存取某一個元 素的內容;然而此函式提供範圍的檢查

fig07_26.cpp (4 of 6)

fig07_26.cpp (5 of 6) Execution Result

fig07_26.cpp (6 of 6) Execution Result 超出索引範圍, at() 將強制終止程 式。