home *** CD-ROM | disk | FTP | other *** search
- // \EXAMPLES\EX09081.CPP
-
- // members of the class Grade
-
- // Files used in this example:
- //-------------------------------------------------------------
- // %F,15,EX09081.H% EX09081.H definition of class Grade
- // EX09081.CPP this file
- // %F,15,EX0908.CPP%EX0908.CPP main() function
- //-------------------------------------------------------------
-
- class Grade;
-
- #include <string.h>
- #include <search.h>
- #include <iostream.h>
- #include "EX09081.H"
-
-
- const LongPair Grade::null = {0, 0};
-
- ostream&
- operator<<( ostream& os, LongPair range)
- {
- // Print the grade range in brackets
- os << "("
- << range.first
- << ", " << range.second
- << ")" << flush;
- return os;
- }
-
-
- ostream&
- operator<<( ostream& os, Grade::GradeAssoc assoc)
- {
- // Print the letter grade
- os << (char *)assoc.letter
- << " "
- << assoc.range
- << flush;
- return os;
- }
-
- char*
- Grade::operator[]( int x)
- {
- GradeAssoc* pAssoc = (GradeAssoc *)NULL;
- GradeAssoc* pCurrAssoc = &GradeList[0];
- long count = NumElem();
-
- // Iterate through the associative array, stop if
- // a range containing the value is found or if
- // we go past the end of the array
-
- do
- {
- if ((pCurrAssoc->range.first <= x)
- && (pCurrAssoc->range.second >= x))
- {
- pAssoc = pCurrAssoc;
- break;
- }
- else
- {
- pCurrAssoc++;
- }
- } while ((--count) > 0);
-
- // return letter grade if found, NULL otherwise
- return (pAssoc ? pAssoc->letter : (char *)NULL);
- }
-
- LongPair
- Grade::operator[]( char* p)
- {
- // Use the "C" library binary search to find the letter grade
- GradeAssoc* pAssoc = (GradeAssoc *)bsearch
- (
- (const void*)p,
- (const void*)GradeList,
- NumElem(),
- sizeof( GradeAssoc),
- &CompareLetter
- );
-
- // if found return numeric range, return null otherwise
- if ( pAssoc == (GradeAssoc *)NULL)
- return null;
- else
- return pAssoc->range;
- };
-
-
- //int _Optlink // IBM CSet II
- int // Microsoft Visual C++, Borland Turbo C++
- CompareLetter( const void* keyval, const void* pvDatum)
- {
- Grade::GradeAssoc* pDatum = (Grade::GradeAssoc *)pvDatum;
- int x = strcmp(
- (char *)keyval,
- (char *)(pDatum->letter)
- );
- return x;
- }
-
-
- // Define and initialize to associative array
- Grade::GradeAssoc Grade::GradeList[] =
- {
- {"A", {80, 100}}, {"B", {70, 79}},
- {"C", {60, 69}}, {"D", {50, 59}},
- {"F", {0, 49}}
- };
-