mit6_096iap11_sol04
TRANSCRIPT
-
8/2/2019 MIT6_096IAP11_sol04
1/4
Lab4 Solutions
2 Multi-Typemin2.1
1 template< t y p e n a m e T >2 T min (const T t1 , const T t2 ) {3
return
t1
< t2
? t1
: t2 ;
4 }
2.21 # d e f i n e min ( x , y ) ( x < y ? x : y )
3 Casting3.1static_cast< T r i a n g l e * > ( p )
orr e i n t e r p r e t _ c a s t< T r i a n g l e * > ( p )3.2dynamic_cast< T r i a n g l e * > ( p )4 Templated Stack4.1
1
-
8/2/2019 MIT6_096IAP11_sol04
2/4
5
10
15
20
25
30
35
40
1 template< class T > class S t a c k ;23 template< class T >4 S t a c k < T > o p e r a t o r+(const S t a c k < T > & s 1 , const S t a c k < T > & s 2 ) ;6 {7 Stack result = s1;89 for(u n s i g n e d i = 0; i 17 class Stack {18 friend S t a c k < T > o p e r a t o r+ < > (const S t a c k < T > & s 1 , const S t a c k < T > &
s 2 ) ;19 v e c t o r < T > i t e m s ;21 p u b l i c:22 bool e m p t y ( ) const { return i t e m s . e m p t y ( ) ; }23 void p u s h (const T & i t e m ) { i t e m s . p u s h _ b a c k ( i t e m ) ; }24 T p o p ( ) {
T last = i t e m s . b a c k ( ) ;26 i t e m s . p o p _ b a c k ( ) ;27 return l a s t ;28 }29 };31 template< class T >32 S t a c k < T > o p e r a t o r+(const S t a c k < T > & s 1 , const S t a c k < T > & s 2 )33 {34 Stack result = s1 ;36 for( u n s i g n e d i = 0; i
-
8/2/2019 MIT6_096IAP11_sol04
3/4
5
10
15
20
25
30
35
5 Graph Representation1 class Graph {2 p r o t e c t e d:3 ma p > o u t g o i n g ;4
p u b l i c:6 G r a p h (const v e c t o r &st artPoints , const v e c t o r &
e n d P o i n t s ) ;7 int n u m O u t g o i n g (const int n o d e I D ) const;8 const v e c t o r < in t> & a d j a c e n t (const int n o d e I D ) const;9 };11 // In a . c p p f i l e . . .1213 # i n c l u d e 14
G r a p h : : G r a p h (const v e c t o r &st artPoints , const v e c t o r &e n d P o i n t s ) {
16 if( s t a r t P o i n t s . s i z e ( ) != e n d P o i n t s . s i z e ( ) ) {17 throw i n v a l i d _ a r g u m e n t ( " S t a r t / e n d point lists differ in
l e n g t h" ) ;18 }19
for(u n s i g n e d i = 0; i & G r a p h : : a d j a c e n t (const int n o d e I D ) const {32 ma p > : : c o n s t _ i t e r a t o r i = o u t g o i n g . f i n d ( n o d e I D )
;33 if( i == o u t g o i n g . e n d ( ) ) {34 throw i n v a l i d _ a r g u m e n t ( " I n v a l i d node ID" ) ;
}36 return i - > s e c o n d ;37 }
3
-
8/2/2019 MIT6_096IAP11_sol04
4/4
MIT OpenCourseWare
http://ocw.mit.edu
6.096 Introduction to C++
January (IAP) 2011
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
http://ocw.mit.edu/http://ocw.mit.edu/termshttp://ocw.mit.edu/termshttp://ocw.mit.edu/