{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

cs246-s11-001-july12

# cs246-s11-001-july12 - CS 246(Spring 2011 Section 1 Tuesday...

This preview shows pages 1–7. Sign up to view the full content.

CS 246 (Spring 2011) – Section 1 Tuesday 12 July The STL

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
CS 246 (Spring 2011) - Section 001 - Tuesday 12 July 2 Today's Agenda Templates Course evaluations today or Thursday
CS 246 (Spring 2011) - Section 001 - Tuesday 12 July 3 2.26 Template A template routine can be used to eliminate duplicated code when only the types of the arguments/return value are different double sum(double a, double b) { return a+b; } int sum(int a, int b) { return a+b; } template<typename T> T sum( T a, T b) { return a+b; } Type of T inferred from arguments

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
CS 246 (Spring 2011) - Section 001 - Tuesday 12 July 4 Template (ctd.) A template type eliminates duplicated code when manipulating different types template<typename T=int, unsigned int N=10> struct Stack { T elems[N]; unsigned int size; Stack() { size = 0; } T top() { return elems[size - 1]; } void push( T e ) { elems[size] = e; size += 1; } T pop() { size -= 1; return elems[size]; } }; template<typename T, unsigned int N> ostream &operator<< ( ostream &os, const Stack<T, N> &stk ) { for ( int i = 0; i < stk.size; i += 1 ) os << stk.elems[i] << " "; return os; }
CS 246 (Spring 2011) - Section 001 - Tuesday 12 July 5 Template (ctd.) We can now create stacks containing different types and re-use the same code for its operations Stack<> s1; // int, 10 Stack<double> s2; // double, 10 Stack<int, 25> s3; // int, 25 Stack<Stack< > > s4; // Stack<int,10>, 10 s1.push(3); s3.push(12); s2.push(3.14); s4.push(s1); int x = s1.pop(); double y = s2.pop();

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
CS 246 (Spring 2011) - Section 001 - Tuesday 12 July 6 2.26.1 Standard Template Library (STL)
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}