cs246-s11-001-july12

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

Info iconThis preview shows pages 1–6. Sign up to view the full content.

View Full Document Right Arrow Icon
CS 246 (Spring 2011) – Section 1 Tuesday 12 July The STL
Background image of page 1

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

View Full DocumentRight Arrow Icon
CS 246 (Spring 2011) - Section 001 - Tuesday 12 July 2 Today's Agenda Templates Course evaluations today or Thursday
Background image of page 2
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
Background image of page 3

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

View Full DocumentRight Arrow Icon
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> for ( int i = 0; i < stk.size; i += 1 ) os << stk.elems[i] << " "; return os; }
Background image of page 4
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();
Background image of page 5

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

View Full DocumentRight Arrow Icon
Image of page 6
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 12/08/2011 for the course CS 246 taught by Professor Wormer during the Spring '08 term at Waterloo.

Page1 / 17

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

This preview shows document pages 1 - 6. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online