Docsity

Generic Algorithms - Object Oriented Programming - Lecture Slides, Slides of Object Oriented Programming

Partial preview of the text

Download Generic Algorithms - Object Oriented Programming - Lecture Slides and more Slides Object Oriented Programming in PDF only on Docsity!

Object-Oriented Programming

(OOP)

Lecture No. 34

Generic Algorithms

A Case Study

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 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

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;

}

Example – Class Template

  • A Vector class template can store data

elements of different types

  • Without templates, we need a separate

Vector class for each data type

…Example – Class Template

template< class T >

class Vector {

private:

int size; T* ptr;

public:

Vector( int = 10 ); Vector( const Vector< T >& ); ~Vector(); int getSize() const;

…Example – Class Template

template< class T >

Vector::Vector( int s ) {

size = s; if ( size != 0 ) ptr = new T[size]; else ptr = 0;

}

…Example – Class Template

template< class T >

Vector:: Vector(

const Vector& copy ) { size = copy.getSize(); if (size != 0) { ptr = new T[size]; for (int i = 0; i < size; i++) ptr[i] = copy.ptr[i]; } else ptr = 0;

}

…Example – Class Template

template< class T >

const Vector& Vector::operator

=( const Vector& right) { if ( this != &right ) { delete [] ptr; size = right.size;

…Example – Class Template

if ( size != 0 ) { ptr = new T[size]; for(int i = 0; i < size;i++) ptr[i] = right.ptr[i]; } else ptr = 0; } return *this;

}