Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Lab 4 Solutions: Template Min Function, Casting, and Templated Stack, Exercises of Data Structures and Algorithms

The solutions to lab 4, which covers template min function, casting, and a templated stack. It includes the code for template min function using both function template and macro, casting using static_cast, reinterpret_cast, and dynamic_cast, and a templated stack implementation using the operator overloading and vector container. Useful for computer science students studying data structures and algorithms.

Typology: Exercises

2011/2012

Uploaded on 07/11/2012

dhanvant
dhanvant 🇮🇳

4.9

(9)

90 documents

1 / 4

Toggle sidebar

Related documents


Partial preview of the text

Download Lab 4 Solutions: Template Min Function, Casting, and Templated Stack and more Exercises Data Structures and Algorithms in PDF only on Docsity! Lab 4 Solutions 2 Multi-Type min 2.1 1 template <typename T> 2 T min( const T t1 , const T t2) { 3 return t1 < t2 ? t1 : t2; 4 } 2.2 1 #define min(x, y) (x < y ? x : y) 3 Casting 3.1 static_cast <Triangle *>(p) or reinterpret_cast <Triangle *>(p) 3.2 dynamic_cast <Triangle *>(p) 4 Templated Stack 4.1 1 Docsity.com 5 10 15 20 25 30 35 40 1 template <class T> class Stack; 2 3 template <class T> 4 Stack <T> operator +( const Stack <T> &s1 , const Stack <T> &s2); 6 { 7 Stack <T > result = s1 ; 8 9 for ( unsigned i = 0; i < s1 . items . size () ; ++ i) { result . items . push_back ( s2 . items [i ]) ; 11 } 12 13 return result ; 14 } 16 template <class T> 17 class Stack { 18 friend Stack <T> operator +<>( const Stack <T> &s1 , const Stack <T> & s2); 19 vector <T> items; 21 public : 22 bool empty() const {return items.empty();} 23 void push( const T &item) {items.push_back(item);} 24 T pop() { T last = items.back(); 26 items.pop_back (); 27 return last; 28 } 29 }; 31 template <class T> 32 Stack <T> operator +( const Stack <T> &s1 , const Stack <T> &s2) 33 { 34 Stack <T> result = s1; 36 for (unsigned i = 0; i < s1.items.size(); ++i) { 37 result.items.push_back(s2.items[i]); 38 } 39 return result; 41 } 2 Docsity.com
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved