faqts : Computers : Programming : Languages : C++

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 29 people (24%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

C++: Array: Size: How to find the total amount of elements in array in C++? [minimum/maximum/size()]

Feb 22nd, 2006 07:48
Knud van Eeden,


----------------------------------------------------------------------
--- Knud van Eeden --- 21 February 2021 - 05:24 pm -------------------
C++: Array: Size: How to find the total amount of elements in array in 
C++? [minimum/maximum/size()]
---
You can use the Standard Template Library (=STL), that has a 
function 'size()':
--- cut here: begin --------------------------------------------------
#include <iostream>
//
#include <vector.h>
//
using namespace std;
//
int main() {
 //
 // --- Declare a vector.
 //
 vector <double> v;
 //
 // --- Read numbers into it.
 //
 v.push_back( 1 );
 v.push_back( 2 );
 v.push_back( 3 );
 v.push_back( 4 );
 v.push_back( 5 );
 v.push_back( 6 );
 //
 // --- Search for minimum value
 //
 double minValue = v[ 0 ];
 //
 for ( int I = 0; I <= v.size() - 1; I++ ) {
  if ( minValue > v[ I ] ) {
   minValue = v[ I ];
  }
 }
 cout << "minimum = ";
 cout << minValue;
 cout << endl;
//
 // --- Search for maximum value
 //
 double maxValue = v[ 0 ];
 //
 for ( int I = 0; I <= v.size() - 1; I++ ) {
  if ( maxValue < v[ I ] ) {
   maxValue = v[ I ];
  }
 }
 cout << "maximum = ";
 cout << maxValue;
 cout << endl;
//
}
--- cut here: end ----------------------------------------------------
otherwise you have to include the size information yourself
(C++ does not have array size information included)
--- cut here: begin --------------------------------------------------
// library: array: minimum + maximum [kn, amv, tu, 21-02-2021 13:42:15]
#include <iostream.h>
//
class arrayC {
 public:
  double FNArrayMinimum( double t[], int minI, int maxI );
  double FNArrayMaximum( double t[], int minI, int maxI );
};
//
double arrayC::FNArrayMinimum( double t[], int minI, int maxI ) {
 double min = t[ minI ];
 //
 for ( int I = minI; I <= maxI; I++ ) {
  if ( min > t[ I ] ) {
   min = t[ I ];
  }
 }
 return( min );
}
//
double arrayC::FNArrayMaximum( double t[], int minI, int maxI ) {
 double max = t[ minI ];
 //
 for ( int I = minI; I <= maxI; I++ ) {
  if ( max < t[ I ] ) {
   max = t[ I ];
  }
 }
 return( max );
}
//
main() {
 arrayC arrayO;
 //
 double t[] = { 1, 2, 3, 4, 5, 6, 7 };
 //
cout << "minimum = ";
cout << arrayO.FNArrayMinimum( t, 0, 6 );
cout << endl;
//
 cout << "maximum = ";
 cout << arrayO.FNArrayMaximum( t, 0, 6 );
 cout << endl;
}
--- cut here: end ----------------------------------------------------
===
Internet: see also:
---
----------------------------------------------------------------------