200 likes | 569 Views
補充 : 樣板 (template) & 例外處理 (exception handling). swaps.cpp :參考值與函數參數 funtemp.cpp :函數樣板 (template) twotemps.cpp :多載樣板 類別樣板 (class template) – Stack<T> 標準 C++ 程式庫 (Standard C++ Library) complex<T> 範例程式 標準樣板程式庫 (Standard Template Library, STL) STL: stack<T> 範例程式 程式設計練習 ( 一 )
E N D
補充: 樣板(template) & 例外處理(exception handling) • swaps.cpp:參考值與函數參數 • funtemp.cpp:函數樣板(template) • twotemps.cpp:多載樣板 • 類別樣板(class template) – Stack<T> • 標準C++程式庫(Standard C++ Library) • complex<T> 範例程式 • 標準樣板程式庫(Standard Template Library, STL) • STL: stack<T> 範例程式 • 程式設計練習(一) • 程式設計練習(二)
swaps.cpp:參考值與函數參數(1/3) #include <iostream.h> void swapr(int & a, int & b);// a, b are aliases for ints void swapp(int * p, int * q);// p, q are addresses of ints void swapv(int a, int b); // a, b are new variables int main(void) { int wallet1 = 300; int wallet2 = 350; cout << "wallet1 = $" << wallet1; cout << " wallet2 = $" << wallet2 << "\n"; cout << "Using references to swap contents:\n"; swapr(wallet1, wallet2); // pass variables cout << "wallet1 = $" << wallet1; cout << " wallet2 = $" << wallet2 << "\n"; cout << "Using pointers to swap contents:\n"; swapp(&wallet1, &wallet2);// pass addresses of variables cout << "wallet1 = $" << wallet1; cout << " wallet2 = $" << wallet2 << "\n";
swaps.cpp:參考值與函數參數(2/3) cout << "Trying to use passing by value:\n"; swapv(wallet1, wallet2); // pass values of variables cout << "wallet1 = $" << wallet1; cout << " wallet2 = $" << wallet2 << "\n"; return 0; } void swapr(int & a, int & b) { // use references (參考值) int temp; temp = a; // use a, b for values of variables a = b; b = temp; } void swapp(int * p, int * q) { // use pointers (指標) int temp; temp = *p; // use *p, *q for values of variables *p = *q; *q = temp; }
swaps.cpp:參考值與函數參數(3/3) void swapv(int a, int b) // try using values (數值) { int temp; temp = a; // use a, b for values of variables a = b; b = temp; } • wallet1 = $300 wallet2 = $350 • Using references to swap contents: • wallet1 = $350 wallet2 = $300 • Using pointers to swap contents: • wallet1 = $300 wallet2 = $350 • Trying to use passing by value: • wallet1 = $300 wallet2 = $350
funtemp.cpp:函數樣板(template) (1/2) #include <iostream.h> template <class Any> // function template prototype void swap(Any &a, Any &b); int main(void) { int i = 10, j = 20; cout << "i, j = " << i << ", " << j << ".\n"; cout << "Using compiler-generated int swapper:\n"; swap(i,j); // generates void swap(int &, int &) cout << "Now i, j = " << i << ", " << j << ".\n"; double x = 24.5, y = 81.7; cout << "x, y = " << x << ", " << y << ".\n"; cout << "Using compiler-generated double swapper:\n"; swap(x,y); //generates void swap(double&, double&) cout << "Now x, y = " << x << ", " << y << ".\n"; return 0; }
funtemp.cpp:函數樣板(template) (2/2) // function prototype definition template <class Any> void swap(Any &a, Any &b) { Any temp; temp = a; a = b; b = temp; }; • i, j = 10, 20. • Using compiler-generated int swapper: • Now i, j = 20, 10. • x, y = 24.5, 81.7. • Using compiler-generated double swapper: • Now x, y = 81.7, 24.5.
類別樣板(class template) – Stack<T> (1/3) • 堆疊(Stack)類別 class Stack{ public: Stack(int size=10); ~Stack(){ delete [] Stk;}; Stack& operator<<(int item); Stack& operator>>(int &item); int IsEmpty() { return (top==-1); } private: int top; int StackSize; int *Stk; }; • 如何能存放不同的資料型態?
類別樣板(class template) – Stack<T> (2/3) #include <iostream.h> template<typename T> class Stack{ public: Stack(int size=10); ~Stack(){ delete [] Stk;}; Stack& operator<<(T item); Stack& operator>>(T &item); int IsEmpty() { return (top==-1); } private: int top; int StackSize; T *Stk; }; template<typename T> Stack<T>::Stack(int size) { Stk = new T [size]; StackSize = size; top = -1; }
類別樣板(class template) – Stack<T> (3/3) template<typename T> Stack<T>& Stack<T>::operator<<(T item) { top++; Stk[top] = item; return *this; } template<typename T> Stack<T>& Stack<T>::operator>>(T &item) { item = Stk[top]; top--; return *this; } main() { float item; Stack<float> s(10); s << 1.1; s << 2.2; s << 3.3; while(!s.IsEmpty()) { s >> item; cout << item << endl; } }
Standard C++ Library • 參考資料: Borland C++ Builder/Help/Standard C++ Library • The Standard C++ Library is a large and comprehensive collection of classes and functions for fine-grained, low-level programming. Within this library, you will find the following components: • The large set of data structures and algorithms formerly known as the Standard Template Library (STL) • An iostream facility • A locale facility • A templatized string class • A templatized complex class for representing complex numbers • A valarray class optimized for handling numeric arrays • A uniform framework for describing the execution environment, using a template class named numeric_limits and specializations for each fundamental datatype • Memory management features • Extensive support for national character sets • Exception handling features
complex<T> 範例程式 #include <complex> #include <iostream> using namespace std; main() { complex<double> x(1.0, 2.0); cout << x + x << x * x; }
STL: Container classes (容器類別) • Container types provided by the Standard C++ Library • vector Random access to elements, efficient insertion at end • vector<bool> Specialization of vector optimized for bool • list Efficient insertion and removal throughout • deque Random access, efficient insertion at front or back • set Elements maintained in order, efficient test for inclusion, insertion, and removal • multiset Set with repeated copies • bitset Bit container templated on size rather than contained type • map Access to values via keys, efficient insertion and removal • multimap Map permitting duplicate keys • string Character container enhanced for string operations • Container adaptors of the Standard C++ Library • stack Insertions and removals only from top • queue Insertions at back, removals from front • priority queue Efficient access and removal of largest values
STL: stack<T> • As a data abstraction, a stack is traditionally defined as any object that implements the operations defined in the following table: • Function Implemented operation • empty() Returns true if the collection is empty • size() Returns number of elements in collection • top() Returns (but does not remove) the topmost element in the stack • push(newElement) Pushes a new element onto the stack • pop() Removes (but does not return) the topmost element from the stack • Programs that use the stack data abstraction should include the file stack: • # include <stack>
STL: stack<T> 範例程式 #include <stack> #include <iostream> using namespace std; main() { stack<int> s; int item; s.push(1); s.push(2); s.push(3); while(!s.empty()) { item = s.top(); s.pop(); cout << item << endl; } }
補充 -- 例外處理(exception handling) try // try-block { … throw exception_type; } // catch handlers catch(exception_type) { handler }
#include <iostream.h> class ErrorScore { public: int score; ErrorScore(int s) { score = s; } }; void check(int score) { if (score < 0 || score > 100) throw ErrorScore(score); }
int main() { int score[4]; try { for(int i=0; i<4; i++) { cin >> score[i]; check(score[i]); } } catch (ErrorScore &err) { printf("Error Score: %d\n", err.score); } return 0; }