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

Generic Algorithms, Print an Array, Arrays of any type, Generic container, Operations, Increment operator, Dereference operator, Class Templates, Facilitates reuse of classes are points you can learn in this Object Oriented Programming lecture.

Typology: Slides

2011/2012

Uploaded on 11/09/2012

bacha
bacha 🇮🇳

4.3

(41)

213 documents

1 / 22

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Object-Oriented Programming
(OOP)
Lecture No. 34
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16

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;

}