Pointers/Memory Allocation   «Prev  Next»
Lesson 15 Dynamic multidimensional arrays
Objective C++ findmax() function

Examine function of C++ dynamic multidimensional array

Program that finds the maximum array element

The findmax() function is a canonical routine for processing such dynamic two-dimensional arrays.

double findmax(const twod& m){
  int  i, j;
  double max = m.base[0][0];
    
  for (i = 0; i < m.column_size; ++i)
     for (j = 0; j < m.row_size; ++j)
        if (m.base[i][j] > max)
           max = m.base[i][j];
  return (max);
}

C++ How to Program
This function works on arbitrary two-dimensional arrays. It finds the maximum element within a given two-dimensional array. The findmax() function is not tied to a particular linear layout of memory, which would be the case for two-dimensional arrays declared automatically on the stack.

Getting the Minimum and Maximum Values for a Numeric Type

Problem: You need to know the largest or smallest representable value for your platform for a numeric type, such as an int or double. Solution: Use the numeric_limits class template in the <limits> header to get, among other things, the largest and smallest possible values for a numeric type (see Example 4-10).
Example 4-10. Getting numeric limits
#include <iostream>
#include <limits>
using namespace std;
template<typename T>
void showMinMax( ) {
cout << "min: " << numeric_limits<T>::min( ) << endl;
cout << "max: " << numeric_limits<T>::max( ) << endl;
cout << endl;
}

int main( ) {
 cout << "short:" << endl;
 showMinMax<short>( );
 cout << "int:" << endl;
 showMinMax<int>( );
 cout << "long:" << endl;
 showMinMax<long>( );
 cout << "float:" << endl;
 showMinMax<float>( );
 cout << "double:" << endl;
 showMinMax<double>( );
 cout << "long double:" << endl;
 showMinMax<long double>( );
 cout << "unsigned short:" << endl;
 showMinMax<unsigned short>( );
 cout << "unsigned int:" << endl;
 showMinMax<unsigned int>( );
 cout << "unsigned long:" << endl;
 showMinMax<unsigned long>( );
}

Finally, let us look at the main() function that ties all the functions we have looked at together.