Object Oriented Programming (OOP) - CS304 Power Point Slides Lecture 34
Object Oriented Programming (OOP) - CS304 Power Point Slides Lecture 34
34
Generic Algorithms
A Case Study
Print an Array
template< typename T > void printArray( T* array, int size ) { for ( int i = 0; i < size; i++ ) cout << array[ i ] << , ; }
Generic Algorithms
const int* find( const int* array, int _size, int x ) { const int* p = array; for (int i = 0; i < _size; i++) { if ( *p == x ) return p; p++; } return 0; }
Generic Algorithms
template< typename T > T* find( T* array,int _size, const T& x ) { T* p = array; for (int i = 0; i < _size; i++) { if ( *p == x ) return p; p++; } return 0; }
Generic Algorithms
template< typename T > T* find( T* array, T* beyond, const T& x ) { T* p = array; while ( p != beyond ) { if ( *p == x ) return p; p++; } return 0; }
Generic Algorithms
template< typename T > T* find( T* array, T* beyond, const T& x ) { T* p = array; while ( p != beyond ) { if ( *p == x ) return p; p++; } return beyond; }
Generic Algorithms
template< typename T > T* find( T* array, T* beyond, const T& x ) { T* p = array; while ( p != beyond && *p != x ) p++; return p; }
Generic Algorithms
This algorithm works fine for arrays of any type
We can make it work for any generic container that supports two operations
Increment operator (++) Dereference operator (*)
Generic Algorithms
template< typename P, typename T > P find( P start, P beyond, const T& x ) { while ( start != beyond && *start != x ) start++; return start; }
Generic Algorithms
int main() { int iArray[5]; iArray[0] = 15; iArray[1] = 7; iArray[2] = 987; int* found; found = find(iArray, iArray + 5, 7); return 0; }
Class Templates
A single class template provides functionality to operate on different types of data
} return *this;
}